craby-gateway 0.30.5 → 0.30.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.
- package/dist-sea/gateway.cjs +3 -3
- package/package.json +1 -1
package/dist-sea/gateway.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`module`),h=require(`node:child_process`),g=require(`node:module`),_=require(`node:url`),v=require(`node:readline`);v=c(v);let y=require(`node:process`);y=c(y);let b=require(`node:util`),x=require(`node:http`),S=require(`node:https`),C=require(`node:stream/promises`),w=require(`path`);w=c(w);let T=require(`node:string_decoder`),E=require(`net`),D=require(`child_process`),O=require(`@anthropic-ai/claude-agent-sdk`);var k={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.30.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:workspace-deps":`pnpm --filter @remote-agent/contracts run build && pnpm --filter @remote-agent/provider-adapters run build`,"build:bundle":`pnpm run build:workspace-deps && tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"mobile:ios-ota:publish":`tsx src/mobileIosOtaInstall.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.118`,"@fastify/compress":`^8.3.1`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const A=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function j(e){let t=e.match(A);return t?t[0]:null}function M(e){return typeof e==`string`?j(e):null}function N(e,t){let n=F(e),r=F(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function P(e,t){return N(e,t)>=0}function F(e){let t=e.match(A);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const I=k,L=I.dependencies??{};function R(e){return L[e]??``}const z={packageName:`craby-gateway`,cliName:`craby-gateway`,version:I.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:R(`@anthropic-ai/claude-agent-sdk`),minimumVersion:M(R(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ee(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=B(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function B(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var V=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),te=o((e=>{var t=V();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),H=o((e=>{var t=V(),n=te();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`module`),h=require(`node:child_process`),g=require(`node:module`),_=require(`node:url`),v=require(`node:readline`);v=c(v);let y=require(`node:process`);y=c(y);let b=require(`node:util`),x=require(`node:http`),S=require(`node:https`),C=require(`node:stream/promises`),w=require(`path`);w=c(w);let T=require(`node:string_decoder`),E=require(`net`),D=require(`child_process`),O=require(`@anthropic-ai/claude-agent-sdk`);var k={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.30.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:workspace-deps":`pnpm --filter @remote-agent/contracts run build && pnpm --filter @remote-agent/provider-adapters run build`,"build:bundle":`pnpm run build:workspace-deps && tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"mobile:ios-ota:publish":`tsx src/mobileIosOtaInstall.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.118`,"@fastify/compress":`^8.3.1`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const A=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function j(e){let t=e.match(A);return t?t[0]:null}function M(e){return typeof e==`string`?j(e):null}function N(e,t){let n=F(e),r=F(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function P(e,t){return N(e,t)>=0}function F(e){let t=e.match(A);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const I=k,L=I.dependencies??{};function R(e){return L[e]??``}const z={packageName:`craby-gateway`,cliName:`craby-gateway`,version:I.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:R(`@anthropic-ai/claude-agent-sdk`),minimumVersion:M(R(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ee(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=B(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function B(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var V=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),te=o((e=>{var t=V();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),H=o((e=>{var t=V(),n=te();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
|
|
3
3
|
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),ne=o((e=>{var t=V(),n=te();function r(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function i(e){let t=new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),re=o((e=>{function t(e,n,r,i){if(i&&typeof i==`object`)if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}return e.call(n,r,i)}e.applyReviver=t})),ie=o((e=>{var t=V();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),ae=o((e=>{var t=re(),n=V(),r=ie();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),oe=o((e=>{var t=ne(),n=te(),r=V(),i=ae(),a=ie(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),this.source=e,Object.defineProperty(this,`tag`,{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let a;for(let e of i){if(e===this)break;e.anchor===this.source&&(a=e)}return a}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let c=n.get(o);if(c||=(a.toJS(o,null,t),n.get(o)),c?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=s(r,o,n)),c.count*c.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return c.res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}else if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}else if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),se=o((e=>{var t=V(),n=ae(),r=ie();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),ce=o((e=>{var t=oe(),n=V(),r=se();function i(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??=c(e),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),le=o((e=>{var t=ce(),n=V(),r=ae();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,`schema`,{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),ue=o((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
|
|
4
4
|
`)?n(r,t):r.includes(`
|
|
5
5
|
`)?`
|
|
@@ -511,9 +511,9 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
511
511
|
\r
|
|
512
512
|
`+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));MD(),DD(),OD();var FD=c(jD(),1);PD();var ID=FD.default;function LD(e){return typeof e==`string`?{text:e,attachments:[]}:{text:e.text,attachments:e.attachments??[]}}var RD=120,zD=class{id;provider;providerMode=`mock`;model;listeners=new Set;pendingApprovals=new Map;closed=!1;constructor(e,t){this.id=t.sessionId,this.provider=e,this.model=t.model}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){this.ensureOpen();let n=LD(e);if((n.attachments?.length??0)>0)throw Error(`Mock provider session does not support image attachments`);let r=n.text;if(this.emit({type:`turn.started`,text:r}),this.emit({type:`item.started`,itemType:`assistant.message`,text:``}),this.requiresApproval(r)){let e=`req_${nT(8)}`;this.pendingApprovals.set(e,{input:r}),this.emit({type:`tool.permission.requested`,requestId:e,toolName:`fs.read`,args:{path:`README.md`},reason:`Mock adapter requires approval for tool-like prompts.`}),this.emit({type:`status.progress`,message:`Waiting for tool approval`});return}await this.streamAssistantText(`(${this.provider}) response: ${r}`)}async interrupt(){this.ensureOpen(),this.emit({type:`turn.failed`,reason:`Interrupted by user`})}async close(){this.closed||=!0}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);if(this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n}),t===`deny`){this.emit({type:`turn.failed`,reason:n??`Tool request denied`});return}await this.streamAssistantText(`Tool approved. Proceeded with request derived from: ${r.input}`)}requiresApproval(e){return/tool|approve|permission|read file|diff/i.test(e)}async streamAssistantText(e){let t=e.split(/\s+/).filter(Boolean),n=``;for(let e of t)n=`${n} ${e}`.trim(),this.emit({type:`item.updated`,text:n}),await BD(RD);this.emit({type:`item.completed`,text:n}),this.emit({type:`turn.completed`,text:n})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function BD(e){return new Promise(t=>setTimeout(t,e))}var VD=class{provider;constructor(e){this.provider=e}async isNativeAvailable(){return!1}async createSession(e){return new zD(this.provider,e)}};function HD(e){let t=KD(WD(e)),n=Z(t.type);return n&&(t.type=UD(n)),t}function UD(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`mcpToolCall`:return`mcp_tool_call`;case`collabAgentToolCall`:return`collab_tool_call`;case`webSearch`:return`web_search`;case`enteredReviewMode`:return`entered_review_mode`;case`exitedReviewMode`:return`exited_review_mode`;case`contextCompaction`:return`context_compaction`;default:return GD(e)}}function WD(e){if(Array.isArray(e))return e.map(e=>WD(e));if(typeof e==`object`&&e){let t={};for(let[n,r]of Object.entries(e))t[GD(n)]=WD(r);return t}return e}function GD(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\-\s/]+/g,`_`).toLowerCase()}function KD(e){return typeof e==`object`&&e?e:{}}function Z(e){if(typeof e==`string`)return e}function qD(e){return typeof e==`string`||typeof e==`number`?String(e):``}var JD=[...`agent_message.agent_message_content_delta.agent_message_delta.agent_reasoning.agent_reasoning_delta.agent_reasoning_raw_content.agent_reasoning_raw_content_delta.agent_reasoning_section_break.apply_patch_approval_request.background_event.collab_agent_interaction_begin.collab_agent_interaction_end.collab_agent_spawn_begin.collab_agent_spawn_end.collab_close_begin.collab_close_end.collab_resume_begin.collab_resume_end.collab_waiting_begin.collab_waiting_end.context_compacted.deprecation_notice.dynamic_tool_call_request.dynamic_tool_call_response.elicitation_request.entered_review_mode.error.exec_approval_request.exec_command_begin.exec_command_end.exec_command_output_delta.exited_review_mode.get_history_entry_response.item_completed.item_started.list_custom_prompts_response.list_remote_skills_response.list_skills_response.mcp_list_tools_response.mcp_startup_complete.mcp_startup_update.mcp_tool_call_begin.mcp_tool_call_end.model_reroute.patch_apply_begin.patch_apply_end.plan_delta.plan_update.raw_response_item.realtime_conversation_closed.realtime_conversation_realtime.realtime_conversation_started.reasoning_content_delta.reasoning_raw_content_delta.remote_skill_downloaded.request_user_input.session_configured.shutdown_complete.skills_update_available.stream_error.task_complete.task_started.terminal_interaction.thread_name_updated.thread_rolled_back.token_count.turn_aborted.turn_diff.undo_completed.undo_started.user_message.view_image_tool_call.warning.web_search_begin.web_search_end`.split(`.`).map(e=>`codex/event/${e}`)],YD=1e4,XD=100,ZD=2e3;function QD(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message,errorStack:e.stack}:{errorValue:String(e)}}function $D(e,t){console.error(`[codex-app-server][diag] ${e} ${JSON.stringify({ts:new Date().toISOString(),...t})}`)}var eO=new Map;async function tO(e){return oO(e).createConnection()}async function nO(){let e=[...eO.values()];await Promise.allSettled(e.map(e=>e.shutdown())),eO.clear()}async function rO(e){let t=eO.size>0?[...eO.values()]:[oO(e)];await Promise.all(t.map(e=>e.restart()))}function iO(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim();return t?aO(t):{command:`codex`,args:[]}}function aO(e){let t=w.default.resolve(e),n=w.default.extname(t).toLowerCase();return n===`.js`||n===`.cjs`||n===`.mjs`?{command:process.execPath,args:[t]}:{command:t,args:[]}}function oO(e){let t=e?.trim()||process.env.REMOTE_AGENT_CODEX_BIN?.trim()||`__default__`,n=eO.get(t);if(n)return n;let r=new sO(e);return eO.set(t,r),r}var sO=class{constructor(e){this.codexBinOverride=e}running=null;startupPromise=null;shutdownPromise=null;async createConnection(){let e=await this.ensureRunning(),t=await lO(e.url,()=>this.buildStartupError(e.stderrTail));return e.connections.add(t),t.onClosed(()=>{e.connections.delete(t)}),t}async shutdown(){if(this.shutdownPromise){await this.shutdownPromise;return}this.shutdownPromise=this.shutdownInternal();try{await this.shutdownPromise}finally{this.shutdownPromise=null}}async restart(){await this.shutdown();let e=await this.ensureRunning();await(await lO(e.url,()=>this.buildStartupError(e.stderrTail))).close()}async shutdownInternal(){let e=this.running;if(this.running=null,this.startupPromise=null,!e)return;e.shuttingDown=!0;let t=[...e.connections];await Promise.allSettled(t.map(e=>e.close())),e.child.exitCode===null&&(e.child.kill(`SIGTERM`),await pO(e.child,ZD)||(e.child.kill(`SIGKILL`),await pO(e.child,ZD)))}async ensureRunning(){if(this.running&&this.running.child.exitCode===null)return this.running;if(this.startupPromise)return this.startupPromise;this.startupPromise=this.startServer();try{let e=await this.startupPromise;return this.running=e,e}finally{this.startupPromise=null}}async startServer(){let e=`ws://127.0.0.1:${await fO()}`,t=iO(this.codexBinOverride),n=(0,D.spawn)(t.command,[...t.args,`app-server`,`--listen`,e],{stdio:[`ignore`,`ignore`,`pipe`],windowsHide:!0}),r={child:n,url:e,stderrTail:``,connections:new Set,shuttingDown:!1};if(n.stderr.setEncoding(`utf8`),n.stderr.on(`data`,e=>{r.stderrTail=`${r.stderrTail}${e}`,r.stderrTail.length>4e3&&(r.stderrTail=r.stderrTail.slice(r.stderrTail.length-4e3))}),n.on(`exit`,(e,t)=>{if(this.running!==r)return;this.running=null;let n=r.stderrTail.trim(),i=`Codex app-server exited unexpectedly (${t?`signal=${t}`:`code=${String(e)}`})${n?`; stderr: ${n}`:``}`;if(!r.shuttingDown)for(let e of r.connections)e.fail(i);r.connections.clear()}),n.on(`error`,e=>{if(this.running!==r)return;this.running=null;let t=`Codex app-server process error: ${String(e)}`;for(let e of r.connections)e.fail(t);r.connections.clear()}),!await dO(e,n,()=>this.buildStartupError(r.stderrTail))){let e=this.buildStartupError(r.stderrTail);throw n.exitCode===null&&(n.kill(`SIGTERM`),await pO(n,ZD)),Error(e)}return r}buildStartupError(e){let t=e.trim();return t?`Failed to start shared Codex app-server; stderr: ${t}`:`Failed to start shared Codex app-server`}},cO=class{constructor(e){this.socket=e,this.socket.on(`message`,this.handleMessage),this.socket.on(`error`,this.handleError),this.socket.on(`close`,this.handleClose)}messageListeners=new Set;failureListeners=new Set;closeListeners=new Set;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server connection is closed`);this.socket.send(e)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}onClosed(e){this.closeListeners.add(e)}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e);this.dispose()}}async close(){if(!this.closed){if(this.closed=!0,this.socket.readyState<=1)try{this.socket.close(1e3,`Client closing`)}catch(e){$D(`connection.close_failed`,{readyState:this.socket.readyState,...QD(e)})}this.dispose()}}handleMessage=e=>{if(this.closed)return;let t=mO(e);if(t!==null)for(let e of this.messageListeners)e(t)};handleError=e=>{this.closed||this.fail(`Codex app-server WebSocket error: ${String(e)}`)};handleClose=(e,t)=>{if(this.closed){this.dispose();return}let n=typeof e==`number`?e:`unknown`,r=t.length>0?`: ${t.toString(`utf8`)}`:``;this.fail(`Codex app-server WebSocket closed (${String(n)})${r}`)};dispose(){this.socket.off(`message`,this.handleMessage),this.socket.off(`error`,this.handleError),this.socket.off(`close`,this.handleClose);for(let e of this.closeListeners)e();this.closeListeners.clear()}};async function lO(e,t){let n=Date.now()+YD,r=null;for(;Date.now()<n;)try{return await uO(e,Math.max(250,n-Date.now()))}catch(e){r=e instanceof Error?e:Error(String(e)),await hO(XD)}throw r??Error(t())}async function uO(e,t){let n=new ID(e);return new Promise((r,i)=>{let a=!1,o=setTimeout(()=>{s(),$D(`connect.timeout`,{url:e,timeoutMs:t,readyState:n.readyState});try{n.close(1e3,`Connect timeout`)}catch(r){$D(`connect.timeout_close_failed`,{url:e,timeoutMs:t,readyState:n.readyState,...QD(r)})}i(Error(`Timed out connecting to Codex app-server at ${e}`))},t),s=()=>{o&&=(clearTimeout(o),null),n.off(`open`,c),n.off(`error`,l),n.off(`close`,u)},c=()=>{a||(a=!0,s(),r(new cO(n)))},l=e=>{a||(a=!0,s(),i(Error(String(e))))},u=(r,o)=>{if(a)return;a=!0,s();let c=typeof r==`number`?r:`unknown`,l=o.length>0?`: ${o.toString(`utf8`)}`:``;$D(`connect.closed_before_open`,{url:e,timeoutMs:t,readyState:n.readyState,closeCode:c,closeReason:l||null}),i(Error(`Connection closed before open (${String(c)})${l}`))};n.on(`open`,c),n.on(`error`,l),n.on(`close`,u)})}async function dO(e,t,n){let r=Date.now()+YD;for(;Date.now()<r;){if(t.exitCode!==null)throw Error(n());try{return await(await uO(e,500)).close(),!0}catch{await hO(XD)}}return!1}async function fO(){let e=(0,E.createServer)();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{t()})});let t=e.address();if(!t||typeof t==`string`)throw Error(`Failed to reserve a local port for Codex app-server`);return t.port}finally{await new Promise(t=>{e.close(()=>t())})}}async function pO(e,t){return e.exitCode===null?new Promise(n=>{let r=!1,i=setTimeout(()=>{r||(r=!0,n(e.exitCode!==null))},t);e.once(`exit`,()=>{r||(r=!0,clearTimeout(i),n(!0))})}):!0}function mO(e){return typeof e==`string`?e:Array.isArray(e)&&e.every(e=>ArrayBuffer.isView(e))?Buffer.concat(e.map(e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength))).toString(`utf8`):e instanceof ArrayBuffer?Buffer.from(e).toString(`utf8`):ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`):null}function hO(e){return new Promise(t=>{setTimeout(t,e)})}var gO=15e3,_O=5e3,vO={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},yO=class{constructor(e,t={}){this.transport=e,this.requestTimeoutMs=t.requestTimeoutMs??gO,this.bindTransport()}pendingRequests=new Map;requestTimeoutMs;nextRequestId=1;closed=!1;unsubscribeMessage=null;unsubscribeFailure=null;async bootstrap(){let e={clientInfo:vO,capabilities:{experimentalApi:!1,optOutNotificationMethods:JD}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.")}async close(){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(`Codex RPC client closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.transport.close())}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r=qD(n),i=new Promise((t,n)=>{let i=setTimeout(()=>{this.pendingRequests.delete(r),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(r,{timeoutId:i,resolve:t,reject:n})});return this.writeMessage({method:e,id:n,params:t}),await i}bindTransport(){this.unsubscribeMessage=this.transport.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.transport.onFailure(e=>{this.handleTransportFailure(e)})}sendNotification(e){this.writeMessage({method:e})}writeMessage(e){this.ensureOpen(),this.transport.send(JSON.stringify(e))}ensureOpen(){if(this.closed)throw Error(`Codex RPC client is closed`)}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{return}let n=Object.prototype.hasOwnProperty.call(t,`id`),r=Z(t.method);if(n&&r){let e=t.id;this.writeMessage({id:e,error:{code:-32601,message:`Unsupported server request: ${r}`}});return}n&&this.handleResponse(t)}handleResponse(e){let t=qD(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=KD(e.error),r=Z(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed: ${r}`));return}n.resolve(e.result)}}handleTransportFailure(e){this.closed||(this.closed=!0,this.rejectPendingRequests(Error(e)))}rejectPendingRequests(e){for(let[t,n]of this.pendingRequests.entries())clearTimeout(n.timeoutId),n.reject(e),this.pendingRequests.delete(t)}};async function bO(e,t={}){let n=new yO(await SO(t),t);try{return await n.bootstrap(),await e(n)}finally{await n.close()}}async function xO(e={}){try{return await bO(async()=>!0,{...e,requestTimeoutMs:e.requestTimeoutMs??_O}),!0}catch{return!1}}async function SO(e){return e.spawnProcess?new wO(e.spawnProcess()):new CO(await tO(e.codexBinOverride))}var CO=class{constructor(e){this.connection=e}send(e){this.connection.send(e)}onMessage(e){return this.connection.onMessage(e)}onFailure(e){return this.connection.onFailure(e)}async close(){await this.connection.close()}},wO=class{constructor(e){this.process=e,this.bindProcess()}messageListeners=new Set;failureListeners=new Set;stdoutBuffer=``;stderrTail=``;closed=!1;send(e){if(this.closed)throw Error(`Codex app-server process transport is closed`);this.process.stdin.write(`${e}
|
|
513
513
|
`)}onMessage(e){return this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}}onFailure(e){return this.failureListeners.add(e),()=>{this.failureListeners.delete(e)}}async close(){this.closed||(this.closed=!0,this.process.stdin.destroyed||this.process.stdin.end(),!this.process.killed&&this.process.exitCode===null&&this.process.kill())}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}),this.process.on(`error`,e=>{this.fail(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.closed)return;let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.fail(`Codex app-server exited unexpectedly (${i})${r}`)})}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
514
|
-
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}},TO=3,EO=250;function DO(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function OO(e,t){let n=Math.max(1,t?.maxAttempts??TO),r=Math.max(0,t?.retryDelayMs??EO),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!DO(e)||t>=n)throw e;r>0&&await kO(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function kO(e){return new Promise(t=>{setTimeout(t,e)})}function AO(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function jO(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var MO=3e4,NO=1e3,PO=2e3,FO=1e3,IO={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`};function LO(e){let t=[];e.text.trim().length>0&&t.push({type:`text`,text:e.text,text_elements:[]});for(let n of e.attachments??[])if(n.kind===`image`){if(!n.localPath)throw Error(`Codex image input requires a local attachment path`);t.push({type:`localImage`,path:n.localPath})}if(t.length===0)throw Error(`Codex turn input requires text or image attachments`);return t}var RO=class e{constructor(e,t,n,r,i,a){this.process=t,this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.logger=e.logger,this.requestTimeoutMs=n,this.closeInterruptTimeoutMs=r,this.closeGraceTimeoutMs=i,this.forceKillTimeoutMs=a,this.processExitPromise=new Promise(e=>{this.resolveProcessExit=e}),this.bindProcess()}id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;activeSandboxPolicy=null;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;requestTimeoutMs;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;interruptRequested=!1;interruptIssuedTurnId;stdoutBuffer=``;stderrTail=``;closeInterruptTimeoutMs;closeGraceTimeoutMs;forceKillTimeoutMs;processExitPromise;resolveProcessExit=null;closePromise=null;static async create(t,n={}){let r=new e(t,n.spawnProcess?.()??zO(),n.requestTimeoutMs??MO,n.closeInterruptTimeoutMs??NO,n.closeGraceTimeoutMs??PO,n.forceKillTimeoutMs??FO);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.resetInterruptState();try{let n=t?.model??this.activeModel,r=AO(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=LO(LD(e)),a=VO(this.activeSessionConfig.reasoningEffort),o,s=HO(t?.mode,n,a),c=UO(this.activeSessionConfig,this.activeSandboxPolicy);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,...c,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&WO(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,...c,effort:`low`,collaborationMode:HO(t?.mode,n,`low`)})}let l=Z(o.turn?.id);l&&(this.activeTurnId=l),this.flushQueuedInterrupt(`turn_start_response`)}catch(e){throw this.turnInProgress=!1,this.resetInterruptState(),e}}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async interrupt(){this.ensureOpen(),this.turnInProgress&&(this.interruptRequested=!0,await this.requestActiveTurnInterrupt())}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;if(r.method===`item/commandExecution/requestApproval`||r.method===`execCommandApproval`){let e={decision:i};this.sendResponse(r.rpcId,e)}else{let e={decision:i};this.sendResponse(r.rpcId,e)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=KO(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:jO(r),inputMethod:n.method})}async bootstrap(){let e={clientInfo:IO,capabilities:{experimentalApi:!0,optOutNotificationMethods:JD}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1},t=await this.sendRequest(`thread/start`,e);return this.activeSandboxPolicy=t.sandbox??null,Z(t.thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1},a=await OO(()=>this.sendRequest(`thread/resume`,i));return this.activeSandboxPolicy=a.sandbox??null,Z(a.thread?.id)}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.consumeStderrChunk(String(e))}),this.process.on(`error`,e=>{this.handleProcessFailure(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.resolveProcessExit?.(),this.resolveProcessExit=null,this.closed){this.log(`info`,`codex app-server process exited during shutdown`,{exitCode:e,signal:t});return}let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.handleProcessFailure(`Codex app-server exited unexpectedly (${i})${r}`)})}async closeInternal(){if(this.closed)return;let e=Date.now(),t={threadId:this.threadId,activeTurnId:this.activeTurnId};this.log(`info`,`codex app-server shutdown starting`,{...t,turnInProgress:this.turnInProgress,pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,closeInterruptTimeoutMs:this.closeInterruptTimeoutMs,closeGraceTimeoutMs:this.closeGraceTimeoutMs,forceKillTimeoutMs:this.forceKillTimeoutMs});let n=await this.tryInterruptTurnForClose();this.log(n.result===`failed`?`warn`:`info`,`codex app-server shutdown turn interrupt completed`,{...t,interrupt:n}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.pendingApprovals.clear(),this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.endProcessStdin();let r=Date.now();if(await this.waitForProcessExit(this.closeGraceTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`graceful_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r});return}this.log(`warn`,`codex app-server shutdown grace period elapsed; sending SIGTERM`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r}),this.tryKillProcess(`SIGTERM`);let i=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigterm_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i});return}this.log(`warn`,`codex app-server shutdown SIGTERM grace elapsed; sending SIGKILL`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i}),this.tryKillProcess(`SIGKILL`);let a=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigkill_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a});return}this.log(`error`,`codex app-server shutdown did not observe process exit after SIGKILL`,{...t,result:`sigkill_timeout`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a})}async tryInterruptTurnForClose(){let e=Date.now();if(!this.threadId||!this.activeTurnId)return{attempted:!1,result:`skipped`,durationMs:Date.now()-e,reason:this.threadId?`missing_active_turn_id`:`missing_thread_id`};try{return await qO(this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:this.activeTurnId}),this.closeInterruptTimeoutMs,`Codex app-server turn/interrupt timed out during close`),{attempted:!0,result:`submitted`,durationMs:Date.now()-e}}catch(t){return{attempted:!0,result:`failed`,durationMs:Date.now()-e,error:String(t)}}}endProcessStdin(){if(!(this.process.stdin.destroyed||this.process.stdin.writableEnded))try{this.process.stdin.end()}catch{}}async waitForProcessExit(e){if(this.process.exitCode!==null)return!0;if(!Number.isFinite(e)||e<=0)return await this.processExitPromise,!0;let t;try{await Promise.race([this.processExitPromise,new Promise(n=>{t=setTimeout(n,e)})])}finally{t&&clearTimeout(t)}return this.process.exitCode!==null}tryKillProcess(e){if(this.process.exitCode===null)try{this.process.kill(e)}catch{}}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,processPid:this.process.pid??void 0,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
514
|
+
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t)for(let e of this.messageListeners)e(t)}}fail(e){if(!this.closed){this.closed=!0;for(let t of this.failureListeners)t(e)}}},TO=3,EO=250;function DO(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function OO(e,t){let n=Math.max(1,t?.maxAttempts??TO),r=Math.max(0,t?.retryDelayMs??EO),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!DO(e)||t>=n)throw e;r>0&&await kO(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function kO(e){return new Promise(t=>{setTimeout(t,e)})}function AO(e,t){return t?{reasoningEffort:t.reasoningEffort??e.reasoningEffort,approvalPolicy:t.approvalPolicy??e.approvalPolicy,sandboxMode:t.sandboxMode??e.sandboxMode,permissionMode:t.permissionMode??e.permissionMode}:{...e}}function jO(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var MO=3e4,NO=1e3,PO=2e3,FO=1e3,IO={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`};function LO(e){let t=[];e.text.trim().length>0&&t.push({type:`text`,text:e.text,text_elements:[]});for(let n of e.attachments??[])if(n.kind===`image`){if(!n.localPath)throw Error(`Codex image input requires a local attachment path`);t.push({type:`localImage`,path:n.localPath})}if(t.length===0)throw Error(`Codex turn input requires text or image attachments`);return t}var RO=class e{constructor(e,t,n,r,i,a){this.process=t,this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.logger=e.logger,this.requestTimeoutMs=n,this.closeInterruptTimeoutMs=r,this.closeGraceTimeoutMs=i,this.forceKillTimeoutMs=a,this.processExitPromise=new Promise(e=>{this.resolveProcessExit=e}),this.bindProcess()}id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;activeSandboxPolicy=null;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;requestTimeoutMs;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;interruptRequested=!1;interruptIssuedTurnId;stdoutBuffer=``;stderrTail=``;closeInterruptTimeoutMs;closeGraceTimeoutMs;forceKillTimeoutMs;processExitPromise;resolveProcessExit=null;closePromise=null;static async create(t,n={}){let r=new e(t,n.spawnProcess?.()??zO(),n.requestTimeoutMs??MO,n.closeInterruptTimeoutMs??NO,n.closeGraceTimeoutMs??PO,n.forceKillTimeoutMs??FO);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.resetInterruptState();try{let n=t?.model??this.activeModel,r=AO(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=LO(LD(e)),a=VO(this.activeSessionConfig.reasoningEffort),o,s=HO(t?.mode,n,a),c=UO(this.activeSessionConfig,this.activeSandboxPolicy);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,...c,model:n??null,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&WO(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,...c,model:n??null,effort:`low`,collaborationMode:HO(t?.mode,n,`low`)})}let l=Z(o.turn?.id);l&&(this.activeTurnId=l),this.flushQueuedInterrupt(`turn_start_response`)}catch(e){throw this.turnInProgress=!1,this.resetInterruptState(),e}}hasThreadOverrideChanges(e){return this.activeSessionConfig.sandboxMode!==e.sandboxMode}async interrupt(){this.ensureOpen(),this.turnInProgress&&(this.interruptRequested=!0,await this.requestActiveTurnInterrupt())}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;if(r.method===`item/commandExecution/requestApproval`||r.method===`execCommandApproval`){let e={decision:i};this.sendResponse(r.rpcId,e)}else{let e={decision:i};this.sendResponse(r.rpcId,e)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=KO(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:jO(r),inputMethod:n.method})}async bootstrap(){let e={clientInfo:IO,capabilities:{experimentalApi:!0,optOutNotificationMethods:JD}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1},t=await this.sendRequest(`thread/start`,e);return this.activeSandboxPolicy=t.sandbox??null,Z(t.thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1},a=await OO(()=>this.sendRequest(`thread/resume`,i));return this.activeSandboxPolicy=a.sandbox??null,Z(a.thread?.id)}bindProcess(){this.process.stdout.setEncoding(`utf8`),this.process.stderr.setEncoding(`utf8`),this.process.stdout.on(`data`,e=>{this.consumeStdoutChunk(String(e))}),this.process.stderr.on(`data`,e=>{this.consumeStderrChunk(String(e))}),this.process.on(`error`,e=>{this.handleProcessFailure(`Codex app-server process error: ${String(e)}`)}),this.process.on(`exit`,(e,t)=>{if(this.resolveProcessExit?.(),this.resolveProcessExit=null,this.closed){this.log(`info`,`codex app-server process exited during shutdown`,{exitCode:e,signal:t});return}let n=this.stderrTail.trim(),r=n?`; stderr: ${n}`:``,i=t?`signal=${t}`:`code=${String(e)}`;this.handleProcessFailure(`Codex app-server exited unexpectedly (${i})${r}`)})}async closeInternal(){if(this.closed)return;let e=Date.now(),t={threadId:this.threadId,activeTurnId:this.activeTurnId};this.log(`info`,`codex app-server shutdown starting`,{...t,turnInProgress:this.turnInProgress,pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,closeInterruptTimeoutMs:this.closeInterruptTimeoutMs,closeGraceTimeoutMs:this.closeGraceTimeoutMs,forceKillTimeoutMs:this.forceKillTimeoutMs});let n=await this.tryInterruptTurnForClose();this.log(n.result===`failed`?`warn`:`info`,`codex app-server shutdown turn interrupt completed`,{...t,interrupt:n}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.pendingApprovals.clear(),this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.endProcessStdin();let r=Date.now();if(await this.waitForProcessExit(this.closeGraceTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`graceful_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r});return}this.log(`warn`,`codex app-server shutdown grace period elapsed; sending SIGTERM`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-r}),this.tryKillProcess(`SIGTERM`);let i=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigterm_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i});return}this.log(`warn`,`codex app-server shutdown SIGTERM grace elapsed; sending SIGKILL`,{...t,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-i}),this.tryKillProcess(`SIGKILL`);let a=Date.now();if(await this.waitForProcessExit(this.forceKillTimeoutMs)){this.log(`info`,`codex app-server shutdown completed`,{...t,result:`sigkill_exit`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a});return}this.log(`error`,`codex app-server shutdown did not observe process exit after SIGKILL`,{...t,result:`sigkill_timeout`,shutdownDurationMs:Date.now()-e,waitDurationMs:Date.now()-a})}async tryInterruptTurnForClose(){let e=Date.now();if(!this.threadId||!this.activeTurnId)return{attempted:!1,result:`skipped`,durationMs:Date.now()-e,reason:this.threadId?`missing_active_turn_id`:`missing_thread_id`};try{return await qO(this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:this.activeTurnId}),this.closeInterruptTimeoutMs,`Codex app-server turn/interrupt timed out during close`),{attempted:!0,result:`submitted`,durationMs:Date.now()-e}}catch(t){return{attempted:!0,result:`failed`,durationMs:Date.now()-e,error:String(t)}}}endProcessStdin(){if(!(this.process.stdin.destroyed||this.process.stdin.writableEnded))try{this.process.stdin.end()}catch{}}async waitForProcessExit(e){if(this.process.exitCode!==null)return!0;if(!Number.isFinite(e)||e<=0)return await this.processExitPromise,!0;let t;try{await Promise.race([this.processExitPromise,new Promise(n=>{t=setTimeout(n,e)})])}finally{t&&clearTimeout(t)}return this.process.exitCode!==null}tryKillProcess(e){if(this.process.exitCode===null)try{this.process.kill(e)}catch{}}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,processPid:this.process.pid??void 0,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}consumeStdoutChunk(e){for(this.stdoutBuffer+=e;;){let e=this.stdoutBuffer.indexOf(`
|
|
515
515
|
`);if(e<0)break;let t=this.stdoutBuffer.slice(0,e).trim();this.stdoutBuffer=this.stdoutBuffer.slice(e+1),t&&this.handleIncomingLine(t)}}consumeStderrChunk(e){this.stderrTail=`${this.stderrTail}${e}`,this.stderrTail.length>2e3&&(this.stderrTail=this.stderrTail.slice(this.stderrTail.length-2e3))}handleIncomingLine(e){let t;try{t=JSON.parse(e)}catch{this.emit({type:`native.raw`,source:`codex.app_server`,parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON line from codex app-server`,line:e});return}this.emit({type:`native.raw`,source:`codex.app_server`,message:t});let n=Z(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let e={method:n,id:t.id,params:t.params};this.handleServerRequest(e);return}if(n){let e={method:n,params:t.params};this.handleNotification(e);return}r&&this.handleResponse(t)}handleResponse(e){let t=qD(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=KD(e.error),r=Z(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`);return}}registerApprovalRequest(e,t,n,r){let i=`req_${nT(8)}`;this.pendingApprovals.set(i,{rpcId:e,method:t,kind:n});let a=KD(r),o=Z(a.threadId);o&&(this.threadId=o),this.emit({type:`tool.permission.requested`,requestId:i,toolName:n===`command`?`command_execution`:`file_change`,reason:Z(a.reason),threadId:o,turnId:Z(a.turnId),itemId:Z(a.itemId),approvalMethod:t,rawParams:WD(a)})}registerUserInputRequest(e,t,n){let r=`req_${nT(8)}`;this.pendingUserInputs.set(r,{rpcId:e,method:t});let i=Z(n.threadId);i&&(this.threadId=i);let a=Array.isArray(n.questions)?n.questions.map(GO).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:r,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:WD(n)})}handleNotification(e){let t=(e,t)=>{let n=KD(KD(e).turn),r=Z(n.status)??t;if(this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),r===`failed`){this.emit({type:`turn.failed`,status:r,turn:WD(n),error:WD(n.error??{})});return}this.emit({type:`turn.completed`,status:r,turn:WD(n)})};if(e.method===`turn/interrupted`){t(e.params,`interrupted`);return}switch(e.method){case`thread/started`:{let t=e.params,n=Z(t.thread?.id);n&&(this.threadId=n),this.emitThreadTitleUpdated(Z(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:WD(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Z(t.threadId);n&&(this.threadId=n),this.emitThreadTitleUpdated(Z(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params,n=Z(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.flushQueuedInterrupt(`turn_started_notification`),this.emit({type:`turn.started`,turn:WD(t.turn)});return}case`turn/completed`:t(e.params);return;case`item/started`:{let t=e.params;this.emit({type:`item.started`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:HD(t.item)});return}case`item/completed`:{let t=e.params;this.emit({type:`item.completed`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:HD(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=KD(e.params);this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:Z(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Z(t.delta)??Z(t.text)??``,original_method:e.method,payload:WD(t)}});return}case`error`:{let t=e.params;this.emit({type:`error`,message:Z(t.error?.message)??`Codex app-server error`,error:WD(t.error),will_retry:t.willRetry===!0,thread_id:Z(t.threadId),turn_id:Z(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=qD(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen(),this.process.stdin.write(`${JSON.stringify(e)}
|
|
516
|
-
`)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=BO(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}handleProcessFailure(e){if(this.closed)return;let t=this.threadId,n=this.activeTurnId;this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.process`,...t?{thread_id:t}:{},...n?{turn_id:n}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}resetInterruptState(){this.interruptRequested=!1,this.interruptIssuedTurnId=void 0}flushQueuedInterrupt(e){this.interruptRequested&&this.requestActiveTurnInterrupt().catch(t=>{this.log(`warn`,`codex app-server queued interrupt failed`,{reason:e,error:t instanceof Error?t.message:String(t)})})}async requestActiveTurnInterrupt(){if(!this.turnInProgress||!this.threadId||!this.activeTurnId)return;let e=this.activeTurnId;if(this.interruptIssuedTurnId!==e){this.interruptIssuedTurnId=e;try{await this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:e})}catch(t){throw this.turnInProgress&&this.activeTurnId===e&&(this.interruptIssuedTurnId=void 0),t}}}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function zO(){let e=iO();return(0,D.spawn)(e.command,[...e.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function BO(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function VO(e){return e?e===`max`?`xhigh`:e:null}function HO(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function UO(e,t){return{approvalPolicy:e.approvalPolicy??null,sandboxPolicy:t}}function WO(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function GO(e){let t=KD(e),n=Z(t.id),r=Z(t.header),i=Z(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=KD(e),n=Z(t.label),r=Z(t.description)??n,i=Z(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:t.isOther===!0,isSecret:t.isSecret===!0,options:o}}function KO(e){let t={};for(let[n,r]of Object.entries(e??{}))n&&(t[n]=Array.isArray(r)?r.map(e=>String(e)):[]);return t}async function qO(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}var JO=3e4,YO=8,XO=160,ZO={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`};function QO(e){let t=[];e.text.trim().length>0&&t.push({type:`text`,text:e.text,text_elements:[]});for(let n of e.attachments??[])if(n.kind===`image`){if(!n.localPath)throw Error(`Codex image input requires a local attachment path`);t.push({type:`localImage`,path:n.localPath})}if(t.length===0)throw Error(`Codex turn input requires text or image attachments`);return t}var $O=class e{id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;activeSandboxPolicy=null;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;bufferedThreadScopedMessages=[];recentAppServerActivity=[];requestTimeoutMs;connection;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;interruptRequested=!1;interruptIssuedTurnId;closePromise=null;unsubscribeMessage=null;unsubscribeFailure=null;static async create(t,n={}){let r=new e(t,n.createConnection?await n.createConnection():await tO(),n.requestTimeoutMs??JO);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}constructor(e,t,n){this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.requestTimeoutMs=n,this.connection=t,this.logger=e.logger,this.bindConnection()}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.resetInterruptState();try{let n=t?.model??this.activeModel,r=AO(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=QO(LD(e)),a=ck(this.activeSessionConfig.reasoningEffort),o,s=lk(t?.mode,n,a),c=uk(this.activeSessionConfig,this.activeSandboxPolicy);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,...c,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&dk(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,...c,effort:`low`,collaborationMode:lk(t?.mode,n,`low`)})}let l=Z(o.turn?.id);l&&(this.activeTurnId=l),this.flushQueuedInterrupt(`turn_start_response`)}catch(e){throw this.turnInProgress=!1,this.resetInterruptState(),e}}async interrupt(){this.ensureOpen(),this.turnInProgress&&(this.interruptRequested=!0,await this.requestActiveTurnInterrupt())}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;switch(r.method){case`item/commandExecution/requestApproval`:case`execCommandApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}case`item/fileChange/requestApproval`:case`applyPatchApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}default:this.sendErrorResponse(r.rpcId,-32601,`Unsupported approval method: ${r.method}`)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=pk(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:jO(r),inputMethod:n.method})}bindConnection(){this.unsubscribeMessage=this.connection.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.connection.onFailure(e=>{this.handleConnectionFailure(e)})}async bootstrap(){let e={clientInfo:ZO,capabilities:{experimentalApi:!0,optOutNotificationMethods:JD}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1},t=await this.sendRequest(`thread/start`,e);return this.activeSandboxPolicy=t.sandbox??null,Z(t.thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1},a=await OO(()=>this.sendRequest(`thread/resume`,i));return this.activeSandboxPolicy=a.sandbox??null,Z(a.thread?.id)}hasThreadOverrideChanges(e,t){return this.activeModel!==e||this.activeSessionConfig.approvalPolicy!==t.approvalPolicy||this.activeSessionConfig.sandboxMode!==t.sandboxMode}async closeInternal(){if(!this.closed)try{await this.interrupt()}catch{}this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState();for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session closed before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let[e,t]of this.pendingUserInputs.entries())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session closed before user input response`,inputMethod:t.method});this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.connection.close()}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{this.recordAppServerActivity({at:new Date().toISOString(),direction:`incoming`,messageKind:`parse_error`,payloadLength:e.length,preview:ak(e)}),this.emitNativeRaw({parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON message from codex app-server`,line:e});return}let n=Z(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let r={method:n,id:t.id,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromServerRequest(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`serverRequest`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleServerRequest(r);return}if(n){let r={method:n,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromNotification(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`notification`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleNotification(r);return}if(r){let n=this.getPendingRequest(t.id);if(!n)return;this.recordIncomingAppServerActivity(t,e.length,n.method);let r=this.extractThreadIdFromResponse(n.method,t.result);r&&this.setThreadIdAndFlushBuffered(r),this.emitNativeRaw({message:t}),this.handleResponse(t),!r&&this.isThreadBindingMethod(n.method)&&!this.hasPendingThreadBindingRequest()&&(this.bufferedThreadScopedMessages.length=0)}}handleResponse(e){let t=qD(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=KD(e.error),r=Z(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`)}}registerApprovalRequest(e,t,n,r){let i=KD(r),a=Z(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${nT(8)}`;this.pendingApprovals.set(o,{rpcId:e,method:t,kind:n}),this.emit({type:`tool.permission.requested`,requestId:o,toolName:n===`command`?`command_execution`:`file_change`,reason:Z(i.reason),threadId:a,turnId:Z(i.turnId),itemId:Z(i.itemId),approvalMethod:t,rawParams:WD(i)})}registerUserInputRequest(e,t,n){let r=Z(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${nT(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(fk).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:i,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:WD(n)})}handleNotification(e){let t=(e,t)=>{let n=KD(e);if(!this.shouldHandleThreadScopedMessage(Z(n.threadId)))return;let r=KD(n.turn),i=Z(r.status)??t;if(this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),i===`failed`){this.emit({type:`turn.failed`,status:i,turn:WD(r),error:WD(r.error??{})});return}this.emit({type:`turn.completed`,status:i,turn:WD(r)})};if(e.method===`turn/interrupted`){t(e.params,`interrupted`);return}switch(e.method){case`thread/started`:{let t=e.params,n=Z(t.thread?.id);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Z(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:WD(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Z(t.threadId);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Z(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;let n=Z(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.flushQueuedInterrupt(`turn_started_notification`),this.emit({type:`turn.started`,turn:WD(t.turn)});return}case`turn/completed`:t(e.params);return;case`item/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.started`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:HD(t.item)});return}case`item/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.completed`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:HD(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=KD(e.params);if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:Z(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Z(t.delta)??Z(t.text)??``,original_method:e.method,payload:WD(t)}});return}case`error`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`error`,message:Z(t.error?.message)??`Codex app-server error`,error:WD(t.error),will_retry:t.willRetry===!0,thread_id:Z(t.threadId),turn_id:Z(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=qD(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen();let t=JSON.stringify(e);this.recordOutgoingAppServerActivity(e,t.length),this.connection.send(t)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=ek(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}handleConnectionFailure(e){if(this.closed)return;let t=ok(e),n=sk(e),r=this.recentAppServerActivity[this.recentAppServerActivity.length-1],i=this.threadId,a=this.activeTurnId;this.log(`error`,`codex app-server websocket session failed`,{failureMessage:e,failureCloseCode:t,failureCloseReason:n,pendingRequestCount:this.pendingRequests.size,pendingRequestMethods:[...new Set([...this.pendingRequests.values()].map(e=>e.method))],pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,bufferedThreadScopedMessageCount:this.bufferedThreadScopedMessages.length,lastAppServerActivity:r,lastAppServerActivityMethod:r?.method,lastAppServerActivityThreadId:r?.threadId,lastAppServerActivityTurnId:r?.turnId,lastAppServerActivityItemId:r?.itemId,lastAppServerActivityDeltaLength:r?.deltaLength,lastAppServerActivityPreview:r?.preview,recentAppServerActivity:[...this.recentAppServerActivity]}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.websocket`,...t===void 0?{}:{close_code:t},...n?{close_reason:n}:{},...i?{thread_id:i}:{},...a?{turn_id:a}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}resetInterruptState(){this.interruptRequested=!1,this.interruptIssuedTurnId=void 0}flushQueuedInterrupt(e){this.interruptRequested&&this.requestActiveTurnInterrupt().catch(t=>{this.log(`warn`,`codex app-server queued interrupt failed`,{reason:e,error:t instanceof Error?t.message:String(t)})})}async requestActiveTurnInterrupt(){if(!this.turnInProgress||!this.threadId||!this.activeTurnId)return;let e=this.activeTurnId;if(this.interruptIssuedTurnId!==e){this.interruptIssuedTurnId=e;try{await this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:e})}catch(t){throw this.turnInProgress&&this.activeTurnId===e&&(this.interruptIssuedTurnId=void 0),t}}}emitNativeRaw(e){this.emit({type:`native.raw`,source:`codex.app_server`,...e})}getPendingRequest(e){return this.pendingRequests.get(qD(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Z(KD(e.params).threadId)}extractThreadIdFromNotification(e){let t=KD(e.params);return Z(t.threadId)||Z(KD(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Z(KD(KD(t).thread).id)}hasPendingThreadBindingRequest(){for(let e of this.pendingRequests.values())if(this.isThreadBindingMethod(e.method))return!0;return!1}isThreadBindingMethod(e){return e===`thread/start`||e===`thread/resume`}setThreadIdAndFlushBuffered(e){if(this.threadId=e,this.bufferedThreadScopedMessages.length===0)return;let t=this.bufferedThreadScopedMessages.splice(0);for(let n of t)n.threadId===e&&(this.emitNativeRaw({message:n.message}),n.kind===`serverRequest`?this.handleServerRequest(n.payload):this.handleNotification(n.payload))}shouldHandleThreadScopedMessage(e){return!!e&&e===this.threadId}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}recordIncomingAppServerActivity(e,t,n){this.recordAppServerActivity(tk({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(tk({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>YO&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-YO)}};function ek(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function tk(e){let t=Z(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=KD(e.message.error),i=rk(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:nk(t,n,e.direction),method:t,requestId:n?qD(e.message.id):void 0,requestMethod:e.responseMethod,threadId:i.threadId,turnId:i.turnId,itemId:i.itemId,payloadLength:e.payloadLength,deltaLength:i.deltaLength,preview:i.preview??ak(Z(r.message))}}function nk(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function rk(e,t){let n=KD(t),r=KD(n.thread),i=KD(n.turn),a=KD(n.item),o=Z(n.delta)??Z(n.text),s=ik(e,n,o);return{threadId:Z(n.threadId)??Z(r.id),turnId:Z(n.turnId)??Z(i.id),itemId:Z(n.itemId)??Z(a.id),deltaLength:typeof o==`string`?o.length:void 0,preview:ak(s)}}function ik(e,t,n){if(e===`item/commandExecution/outputDelta`||e===`item/fileChange/outputDelta`||e===`item/agentMessage/delta`||e===`item/plan/delta`||e===`item/reasoning/summaryTextDelta`||e===`item/reasoning/textDelta`)return n;if(e===`error`)return Z(KD(t.error).message)??Z(t.message)}function ak(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=XO?t:`${t.slice(0,XO)}...`}function ok(e){let t=/WebSocket closed \((\d+)\)/.exec(e);if(!t)return;let n=Number.parseInt(t[1]??``,10);return Number.isFinite(n)?n:void 0}function sk(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function ck(e){return e?e===`max`?`xhigh`:e:null}function lk(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function uk(e,t){return{approvalPolicy:e.approvalPolicy??null,sandboxPolicy:t}}function dk(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function fk(e){let t=KD(e),n=Z(t.id),r=Z(t.header),i=Z(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=KD(e),n=Z(t.label),r=Z(t.description)??n,i=Z(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:!!t.isOther,isSecret:!!t.isSecret,options:o}}function pk(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var mk=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new VD(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await xO()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=e.codexAppServerTransport===`stdio`?this.runtime.createNativeSession??RO.create:this.runtime.createWebSocketNativeSession??$O.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}};async function hk(e,t){let n=[],r=null,i=xk(t?.maxThreads),a=t?.sortKey,o=t?.updatedAfterUnixSeconds;do{let t=i===null?100:Math.max(0,i-n.length);if(t===0)break;let s=await gk({cwd:e,archived:!1,cursor:r,limit:i===null?100:Math.min(100,t),sortKey:a}),c=!1;for(let t of s.threads)if(t.cwd===e){if(o!==void 0&&t.updatedAt<o){if(a===`updated_at`){c=!0;break}continue}if(n.push(t),i!==null&&n.length>=i){c=!0;break}}if(c)break;r=s.nextCursor}while(r);return n}async function gk(e){return bO(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>bk(e)),nextCursor:n.nextCursor}})}async function _k(e,t=!0){return bO(async n=>bk((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function vk(e){return bO(async t=>{let n=!1;try{let r=await OO(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,await wk(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function yk(){let e=[],t=null;do{let n=await bO(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>Ck(e))),t=n.nextCursor}while(t);return e}function bk(e){let t=Z(KD(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,status:Sk(e.status),path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:Ek(e.source),gitInfo:e.gitInfo?KD(WD(e.gitInfo)):null,turns:e.turns.map(e=>Tk(e))}}function xk(e){return e===void 0||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}function Sk(e){let t=Z(KD(e).type);switch(t){case`active`:case`idle`:case`notLoaded`:case`systemError`:return t;default:return`idle`}}function Ck(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}async function wk(e){let t=new Date(e.thread.updatedAt*1e3).toISOString();return kk({model:Dk(e.model),reasoningEffort:Ok(e.reasoningEffort),approvalPolicy:null,sandboxMode:null,updatedAt:t})}function Tk(e){return{id:e.id,status:e.status,error:e.error?KD(WD(e.error)):null,items:e.items.map(e=>HD(e))}}function Ek(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}function Dk(e){return Z(e)?.trim()||void 0}function Ok(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function kk(e){let t=e.approvalPolicy!==null||e.sandboxMode!==null;return e.model||e.reasoningEffort!==null||t?{model:e.model,sessionTurnConfig:{mode:`default`,model:e.model??null,reasoningEffort:e.reasoningEffort,...t?{execution:{codex:{approvalPolicy:e.approvalPolicy,sandboxMode:e.sandboxMode}}}:{}},sessionTurnConfigUpdatedAt:e.updatedAt??``}:null}var Ak=5e3,jk=`Request interrupted by user`;function Mk(e){if((e.attachments?.length??0)===0)return e.text;let t=Nk(e);return(async function*(){yield{type:`user`,message:{role:`user`,content:t},parent_tool_use_id:null}})()}function Nk(e){let t=[];e.text.trim().length>0&&t.push({type:`text`,text:e.text});for(let n of e.attachments??[])if(n.kind===`image`){if(!n.dataBase64)throw Error(`Claude image input requires base64 attachment data`);t.push({type:`image`,source:{type:`base64`,media_type:n.mimeType,data:n.dataBase64}})}if(t.length===0)throw Error(`Claude turn input requires text or image attachments`);return t}function Pk(e){let t=[];e.text.trim().length>0&&t.push({type:`text`,text:e.text});for(let n of e.attachments??[])t.push({type:`image`,source:n.localPath?{type:`local_file`,path:n.localPath}:{type:`base64`,media_type:n.mimeType},remote_agent_attachment:Fk(n)});return t}function Fk(e){return{id:e.id,kind:e.kind,mimeType:e.mimeType,fileName:e.fileName,width:e.width,height:e.height,sizeBytes:e.sizeBytes,...e.localPath?{locator:{kind:`absolute`,path:e.localPath}}:{}}}var Ik=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;activeTurnTerminalEmitted=!1;closePromise=null;interruptFallbackTimer=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1,this.clearInterruptFallbackTimer(),this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=AO(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=LD(e),r=new AbortController,i=this.createQuery({prompt:Mk(n),model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:r,canUseTool:this.handleCanUseTool});this.activeAbortController=r,this.activeQuery=i,this.emitSyntheticUserInputEvents(n),this.startQueryLoop(i)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0;let e=this.activeQuery,t=this.activeAbortController;if(!e)return;let n=!1;if(typeof e.interrupt==`function`)try{await e.interrupt(),n=!0}catch{}if(n){this.armInterruptFallback(e,t);return}typeof e.close==`function`&&e.close(),t?.abort()}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=Vk(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:jO(r),tool_name:n.toolName,itemId:n.toolUseID,turn_id:n.turnId,questions:n.questions,answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{let t=null;try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=cA(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:lA(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(n){if(this.closed||this.activeQuery!==e)return;let r=n instanceof Error?n.message:String(n);this.interruptRequested?t=r:this.emit({type:`error`,message:r})}finally{if(this.closed||this.activeQuery!==e)return;if(this.clearInterruptFallbackTimer(),this.interruptRequested&&!this.activeTurnTerminalEmitted){let e=this.buildInterruptedTerminalEvents(t??jk);for(let t of e)this.emit(t)}this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.clearInterruptFallbackTimer();let e=this.activeAbortController;this.activeAbortController=null;let t=this.activeQuery;if(this.activeQuery=null,!this.activeTurnTerminalEmitted&&typeof t?.interrupt==`function`)try{await t.interrupt()}catch{}typeof t?.close==`function`&&t.close(),e?.abort(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>Rk(e,t)?this.requestUserInput(e,t,n):Lk(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${nT(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=zk(t),i=`req_${nT(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,itemId:n.toolUseID,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((a,o)=>{if(n.signal.aborted){a({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emitUserInputResolved(i,{toolName:e,toolUseID:n.toolUseID,turnId:this.activeTurnId,input:t,questions:r},`interrupted`,`Operation aborted`,`abort`);return}let s=()=>{n.signal.removeEventListener(`abort`,s);let e=this.pendingUserInputRequests.get(i);e&&(this.pendingUserInputRequests.delete(i),a({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emitUserInputResolved(i,e,`interrupted`,`Operation aborted`,`abort`))};n.signal.addEventListener(`abort`,s,{once:!0}),this.pendingUserInputRequests.set(i,{toolName:e,toolUseID:n.toolUseID,turnId:this.activeTurnId,input:t,questions:r,resolve:e=>{n.signal.removeEventListener(`abort`,s),a(e)},reject:e=>{n.signal.removeEventListener(`abort`,s),o(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries()){n.resolve({behavior:`deny`,message:e,interrupt:!0});let r=e===`Turn finished`?`turn_finished`:`session_end`,i=e===`Turn finished`?`expired`:`cancelled`;this.emitUserInputResolved(t,n,i,e,r)}this.pendingUserInputRequests.clear()}emitUserInputResolved(e,t,n,r,i){this.emit({type:`user.input.resolved`,requestId:e,status:n,answeredCount:0,reason:r,tool_name:t.toolName,itemId:t.toolUseID,turn_id:t.turnId,questions:t.questions,source_event_type:i})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1}armInterruptFallback(e,t){this.clearInterruptFallbackTimer(),this.interruptFallbackTimer=setTimeout(()=>{this.closed||!this.turnInProgress||!this.interruptRequested||this.activeQuery!==e||(e.close?.(),t?.abort())},Ak)}clearInterruptFallbackTimer(){this.interruptFallbackTimer&&=(clearTimeout(this.interruptFallbackTimer),null)}captureResumeSessionId(e){let t=cA(e),n=lA(t.session_id)??lA(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.text.trim()&&(e.attachments?.length??0)===0)return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${nT(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:Pk(e)},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=pA(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=lA(e.tool_id)??lA(e.tool_use_id)??dA(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=lA(e.uuid);if(n)return this.activeToolItemId=n,n;let r=mA(lA(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}buildInterruptedTerminalEvents(e){return this.activeTurnTerminalEmitted=!0,[...this.buildAssistantCompletionTailEvent(),{type:`turn.failed`,status:`interrupted`,error:{message:e},turn_id:this.activeTurnId,source_event_type:`abort`}]}mapClaudeMessage(e){let t=cA(e),n=lA(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!tA(t))return[];let n=cA(t.message),r=nA(n),i=rA(n);return!r&&i.length===0?[]:[{type:`item.completed`,item:{id:lA(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,...r?{text:r}:{},...i.length>0?{attachments:i}:{},turn_id:this.activeTurnId,source_event_type:lA(t.source_event_type)??`user`}}]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=eA(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=cA(t.event);if(lA(e.type)===`message_start`){let t=pA(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=iA(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||lA(t.subtype)?.startsWith(`error_`)===!0){let n=oA(t,this.interruptRequested),r=aA(t,n);return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.failed`,...n?{status:`interrupted`}:{},error:{message:r},usage:sA(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:sA(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=lA(t.summary)??`tool summary`,i=lA(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=lA(t.tool_name)??`tool`,i=lA(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=lA(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(lA(t.session_id)??lA(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:lA(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=lA(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=Hk(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=Uk(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=Wk({toolUse:n,toolUseId:t.toolUseId,isError:t.isError,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function Lk(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function Rk(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function zk(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=Bk(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function Bk(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function Vk(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function Hk(e){let t=cA(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=cA(e);if(t.type!==`tool_use`)continue;let n=lA(t.id),i=lA(t.name),a=cA(t.input);if(!(!n||!i)){if(i===`Task`){let e=lA(a.subagent_type),t=lA(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:lA(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=lA(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=lA(a.file_path);r.push({id:n,toolName:`Write`,title:Yk(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function Uk(e){let t=cA(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=cA(e);if(t.type!==`tool_result`)continue;let n=lA(t.tool_use_id);if(n)return{toolUseId:n,isError:t.is_error===!0}}return null}function Wk(e){let t=cA(e.raw.tool_use_result),n=Gk(t.content)??nA(cA(e.raw.message)),r=cA(t.usage),i=fA(t.totalTokens)??fA(r.total_tokens)??fA(r.output_tokens),a=fA(t.totalToolUseCount),o=fA(t.totalDurationMs),s=lA(t.agentId),c=lA(t.filePath)??e.toolUse.filePath,l=e.isError?`failed`:`completed`;if(e.toolUse.toolName===`Task`){let t=e.isError?`Failed`:qk(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:l,status_label:t,is_error:e.isError,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=Kk(t)??n,a=e.isError?`Failed`:`Done`;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:a,status:l,status_label:a,is_error:e.isError,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=uA(t.content),r=e.isError?`Failed`:Jk(Zk(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:l,status_label:r,is_error:e.isError,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function Gk(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=cA(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
|
|
516
|
+
`)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=BO(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}handleProcessFailure(e){if(this.closed)return;let t=this.threadId,n=this.activeTurnId;this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.process`,...t?{thread_id:t}:{},...n?{turn_id:n}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}resetInterruptState(){this.interruptRequested=!1,this.interruptIssuedTurnId=void 0}flushQueuedInterrupt(e){this.interruptRequested&&this.requestActiveTurnInterrupt().catch(t=>{this.log(`warn`,`codex app-server queued interrupt failed`,{reason:e,error:t instanceof Error?t.message:String(t)})})}async requestActiveTurnInterrupt(){if(!this.turnInProgress||!this.threadId||!this.activeTurnId)return;let e=this.activeTurnId;if(this.interruptIssuedTurnId!==e){this.interruptIssuedTurnId=e;try{await this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:e})}catch(t){throw this.turnInProgress&&this.activeTurnId===e&&(this.interruptIssuedTurnId=void 0),t}}}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}};function zO(){let e=iO();return(0,D.spawn)(e.command,[...e.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function BO(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function VO(e){return e?e===`max`?`xhigh`:e:null}function HO(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function UO(e,t){return{approvalPolicy:e.approvalPolicy??null,sandboxPolicy:t}}function WO(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function GO(e){let t=KD(e),n=Z(t.id),r=Z(t.header),i=Z(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=KD(e),n=Z(t.label),r=Z(t.description)??n,i=Z(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:t.isOther===!0,isSecret:t.isSecret===!0,options:o}}function KO(e){let t={};for(let[n,r]of Object.entries(e??{}))n&&(t[n]=Array.isArray(r)?r.map(e=>String(e)):[]);return t}async function qO(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}var JO=3e4,YO=8,XO=160,ZO={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`};function QO(e){let t=[];e.text.trim().length>0&&t.push({type:`text`,text:e.text,text_elements:[]});for(let n of e.attachments??[])if(n.kind===`image`){if(!n.localPath)throw Error(`Codex image input requires a local attachment path`);t.push({type:`localImage`,path:n.localPath})}if(t.length===0)throw Error(`Codex turn input requires text or image attachments`);return t}var $O=class e{id;provider=`codex`;providerMode=`native`;model;cwd;resumeSessionId;activeModel;activeSessionConfig;activeSandboxPolicy=null;listeners=new Set;deferredEventsUntilListener=[];pendingRequests=new Map;pendingApprovals=new Map;pendingUserInputs=new Map;bufferedThreadScopedMessages=[];recentAppServerActivity=[];requestTimeoutMs;connection;logger;nextRequestId=1;closed=!1;threadId;threadTitle;activeTurnId;turnInProgress=!1;interruptRequested=!1;interruptIssuedTurnId;closePromise=null;unsubscribeMessage=null;unsubscribeFailure=null;static async create(t,n={}){let r=new e(t,n.createConnection?await n.createConnection():await tO(),n.requestTimeoutMs??JO);try{return await r.bootstrap(),r}catch(e){throw await r.close(),e}}constructor(e,t,n){this.id=e.sessionId,this.model=e.model,this.activeModel=e.model,this.cwd=e.cwd,this.activeSessionConfig={...e.sessionConfig??{}},this.resumeSessionId=e.resumeSessionId,this.requestTimeoutMs=n,this.connection=t,this.logger=e.logger,this.bindConnection()}onEvent(e){let t=this.listeners.size===0&&this.deferredEventsUntilListener.length>0;if(this.listeners.add(e),t){let t=this.deferredEventsUntilListener.splice(0);for(let n of t)e(n)}return()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.threadId}async sendInput(e,t){if(this.ensureOpen(),!this.threadId)throw Error(`Codex app-server thread is not initialized`);if(this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.resetInterruptState();try{let n=t?.model??this.activeModel,r=AO(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=QO(LD(e)),a=ck(this.activeSessionConfig.reasoningEffort),o,s=lk(t?.mode,n,a),c=uk(this.activeSessionConfig,this.activeSandboxPolicy);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,...c,model:n??null,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&dk(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,...c,model:n??null,effort:`low`,collaborationMode:lk(t?.mode,n,`low`)})}let l=Z(o.turn?.id);l&&(this.activeTurnId=l),this.flushQueuedInterrupt(`turn_start_response`)}catch(e){throw this.turnInProgress=!1,this.resetInterruptState(),e}}async interrupt(){this.ensureOpen(),this.turnInProgress&&(this.interruptRequested=!0,await this.requestActiveTurnInterrupt())}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){this.ensureOpen();let r=this.pendingApprovals.get(e);if(!r)throw Error(`Unknown approval request: ${e}`);let i=t===`allow`?`accept`:`decline`;switch(r.method){case`item/commandExecution/requestApproval`:case`execCommandApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}case`item/fileChange/requestApproval`:case`applyPatchApproval`:{let e={decision:i};this.sendResponse(r.rpcId,e);break}default:this.sendErrorResponse(r.rpcId,-32601,`Unsupported approval method: ${r.method}`)}this.pendingApprovals.delete(e),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,nativeDecision:i,approvalMethod:r.method,approvalKind:r.kind})}async respondUserInput(e,t){this.ensureOpen();let n=this.pendingUserInputs.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);let r=pk(t),i={answers:Object.fromEntries(Object.entries(r).map(([e,t])=>[e,{answers:t}]))};this.sendResponse(n.rpcId,i),this.pendingUserInputs.delete(e),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:jO(r),inputMethod:n.method})}bindConnection(){this.unsubscribeMessage=this.connection.onMessage(e=>{this.handleIncomingMessage(e)}),this.unsubscribeFailure=this.connection.onFailure(e=>{this.handleConnectionFailure(e)})}async bootstrap(){let e={clientInfo:ZO,capabilities:{experimentalApi:!0,optOutNotificationMethods:JD}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1},t=await this.sendRequest(`thread/start`,e);return this.activeSandboxPolicy=t.sandbox??null,Z(t.thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1},a=await OO(()=>this.sendRequest(`thread/resume`,i));return this.activeSandboxPolicy=a.sandbox??null,Z(a.thread?.id)}hasThreadOverrideChanges(e){return this.activeSessionConfig.sandboxMode!==e.sandboxMode}async closeInternal(){if(!this.closed)try{await this.interrupt()}catch{}this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState();for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session closed before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let[e,t]of this.pendingUserInputs.entries())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session closed before user input response`,inputMethod:t.method});this.pendingUserInputs.clear(),this.rejectPendingRequests(Error(`Session ${this.id} is closed`)),this.unsubscribeMessage?.(),this.unsubscribeFailure?.(),this.unsubscribeMessage=null,this.unsubscribeFailure=null,await this.connection.close()}handleIncomingMessage(e){let t;try{t=JSON.parse(e)}catch{this.recordAppServerActivity({at:new Date().toISOString(),direction:`incoming`,messageKind:`parse_error`,payloadLength:e.length,preview:ak(e)}),this.emitNativeRaw({parse_error:!0,line:e}),this.emit({type:`status.progress`,message:`Received non-JSON message from codex app-server`,line:e});return}let n=Z(t.method),r=Object.prototype.hasOwnProperty.call(t,`id`);if(n&&r){let r={method:n,id:t.id,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromServerRequest(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`serverRequest`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleServerRequest(r);return}if(n){let r={method:n,params:t.params};this.recordIncomingAppServerActivity(t,e.length);let i=this.extractThreadIdFromNotification(r),a=this.classifyThreadScopedMessage(i);if(a===`buffer`&&i){this.bufferedThreadScopedMessages.push({kind:`notification`,threadId:i,message:t,payload:r});return}if(a===`ignore`)return;this.emitNativeRaw({message:t}),this.handleNotification(r);return}if(r){let n=this.getPendingRequest(t.id);if(!n)return;this.recordIncomingAppServerActivity(t,e.length,n.method);let r=this.extractThreadIdFromResponse(n.method,t.result);r&&this.setThreadIdAndFlushBuffered(r),this.emitNativeRaw({message:t}),this.handleResponse(t),!r&&this.isThreadBindingMethod(n.method)&&!this.hasPendingThreadBindingRequest()&&(this.bufferedThreadScopedMessages.length=0)}}handleResponse(e){let t=qD(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=KD(e.error),r=Z(t.message)??JSON.stringify(t);n.reject(Error(`Codex app-server request failed (${n.method}): ${r}`));return}n.resolve(e.result)}}handleServerRequest(e){switch(e.method){case`item/commandExecution/requestApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`item/fileChange/requestApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`execCommandApproval`:this.registerApprovalRequest(e.id,e.method,`command`,e.params);return;case`applyPatchApproval`:this.registerApprovalRequest(e.id,e.method,`file`,e.params);return;case`item/tool/requestUserInput`:this.registerUserInputRequest(e.id,e.method,e.params);return;default:this.sendErrorResponse(e.id,-32601,`Unsupported server request: ${e.method}`)}}registerApprovalRequest(e,t,n,r){let i=KD(r),a=Z(i.threadId);if(!this.shouldHandleThreadScopedMessage(a))return;let o=`req_${nT(8)}`;this.pendingApprovals.set(o,{rpcId:e,method:t,kind:n}),this.emit({type:`tool.permission.requested`,requestId:o,toolName:n===`command`?`command_execution`:`file_change`,reason:Z(i.reason),threadId:a,turnId:Z(i.turnId),itemId:Z(i.itemId),approvalMethod:t,rawParams:WD(i)})}registerUserInputRequest(e,t,n){let r=Z(n.threadId);if(!this.shouldHandleThreadScopedMessage(r))return;let i=`req_${nT(8)}`;this.pendingUserInputs.set(i,{rpcId:e,method:t});let a=Array.isArray(n.questions)?n.questions.map(fk).filter(e=>e!==null):[];this.emit({type:`user.input.requested`,requestId:i,threadId:n.threadId,turnId:n.turnId,itemId:n.itemId,questions:a,inputMethod:t,rawParams:WD(n)})}handleNotification(e){let t=(e,t)=>{let n=KD(e);if(!this.shouldHandleThreadScopedMessage(Z(n.threadId)))return;let r=KD(n.turn),i=Z(r.status)??t;if(this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),i===`failed`){this.emit({type:`turn.failed`,status:i,turn:WD(r),error:WD(r.error??{})});return}this.emit({type:`turn.completed`,status:i,turn:WD(r)})};if(e.method===`turn/interrupted`){t(e.params,`interrupted`);return}switch(e.method){case`thread/started`:{let t=e.params,n=Z(t.thread?.id);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Z(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:WD(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=Z(t.threadId);if(!this.shouldHandleThreadScopedMessage(n))return;this.emitThreadTitleUpdated(Z(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;let n=Z(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.flushQueuedInterrupt(`turn_started_notification`),this.emit({type:`turn.started`,turn:WD(t.turn)});return}case`turn/completed`:t(e.params);return;case`item/started`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.started`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:HD(t.item)});return}case`item/completed`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.completed`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:HD(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`agent_message`,text:t.delta,original_method:e.method,payload:{delta:t.delta}}});return}case`item/commandExecution/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`command_execution`,aggregated_output:t.delta,output_delta:t.delta}});return}case`item/fileChange/outputDelta`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:t.itemId,type:`file_change`,output_delta:t.delta}});return}case`item/plan/delta`:case`item/reasoning/summaryTextDelta`:case`item/reasoning/summaryPartAdded`:case`item/reasoning/textDelta`:{let t=KD(e.params);if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`item.updated`,thread_id:Z(t.threadId),turn_id:Z(t.turnId),item:{id:Z(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:Z(t.delta)??Z(t.text)??``,original_method:e.method,payload:WD(t)}});return}case`error`:{let t=e.params;if(!this.shouldHandleThreadScopedMessage(Z(t.threadId)))return;this.emit({type:`error`,message:Z(t.error?.message)??`Codex app-server error`,error:WD(t.error),will_retry:t.willRetry===!0,thread_id:Z(t.threadId),turn_id:Z(t.turnId)});return}default:return}}async sendRequest(e,t){this.ensureOpen();let n=this.nextRequestId;this.nextRequestId+=1;let r={method:e,id:n,params:t},i=qD(n),a=new Promise((t,n)=>{let r=setTimeout(()=>{this.pendingRequests.delete(i),n(Error(`Codex app-server request timed out: ${e}`))},this.requestTimeoutMs);this.pendingRequests.set(i,{method:e,timeoutId:r,resolve:t,reject:n})});return this.writeMessage(r),await a}sendNotification(e){let t={method:e};this.writeMessage(t)}sendResponse(e,t){this.writeMessage({id:e,result:t})}sendErrorResponse(e,t,n){this.writeMessage({id:e,error:{code:t,message:n}})}writeMessage(e){this.ensureOpen();let t=JSON.stringify(e);this.recordOutgoingAppServerActivity(e,t.length),this.connection.send(t)}emit(e){if(this.listeners.size===0&&e.type!==`native.raw`){this.deferredEventsUntilListener.push(e);return}for(let t of this.listeners)t(e)}emitThreadTitleUpdated(e,t,n={}){let r=ek(e);!r||r===this.threadTitle||(this.threadTitle=r,this.emit({type:`thread.title.updated`,title:r,source:t,...n}))}handleConnectionFailure(e){if(this.closed)return;let t=ok(e),n=sk(e),r=this.recentAppServerActivity[this.recentAppServerActivity.length-1],i=this.threadId,a=this.activeTurnId;this.log(`error`,`codex app-server websocket session failed`,{failureMessage:e,failureCloseCode:t,failureCloseReason:n,pendingRequestCount:this.pendingRequests.size,pendingRequestMethods:[...new Set([...this.pendingRequests.values()].map(e=>e.method))],pendingApprovalCount:this.pendingApprovals.size,pendingUserInputCount:this.pendingUserInputs.size,bufferedThreadScopedMessageCount:this.bufferedThreadScopedMessages.length,lastAppServerActivity:r,lastAppServerActivityMethod:r?.method,lastAppServerActivityThreadId:r?.threadId,lastAppServerActivityTurnId:r?.turnId,lastAppServerActivityItemId:r?.itemId,lastAppServerActivityDeltaLength:r?.deltaLength,lastAppServerActivityPreview:r?.preview,recentAppServerActivity:[...this.recentAppServerActivity]}),this.closed=!0,this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),this.rejectPendingRequests(Error(e));for(let[e,t]of this.pendingApprovals.entries())this.emit({type:`tool.permission.resolved`,requestId:e,decision:`deny`,reason:`Session terminated before approval response`,nativeDecision:`decline`,approvalMethod:t.method,approvalKind:t.kind});this.pendingApprovals.clear();for(let e of this.pendingUserInputs.keys())this.emit({type:`user.input.resolved`,requestId:e,status:`expired`,answeredCount:0,reason:`Session terminated before user input response`});this.pendingUserInputs.clear(),this.emit({type:`error.runtime`,message:e,source:`codex.app_server.websocket`,...t===void 0?{}:{close_code:t},...n?{close_reason:n}:{},...i?{thread_id:i}:{},...a?{turn_id:a}:{}})}rejectPendingRequests(e){for(let t of this.pendingRequests.values())clearTimeout(t.timeoutId),t.reject(e);this.pendingRequests.clear()}resetInterruptState(){this.interruptRequested=!1,this.interruptIssuedTurnId=void 0}flushQueuedInterrupt(e){this.interruptRequested&&this.requestActiveTurnInterrupt().catch(t=>{this.log(`warn`,`codex app-server queued interrupt failed`,{reason:e,error:t instanceof Error?t.message:String(t)})})}async requestActiveTurnInterrupt(){if(!this.turnInProgress||!this.threadId||!this.activeTurnId)return;let e=this.activeTurnId;if(this.interruptIssuedTurnId!==e){this.interruptIssuedTurnId=e;try{await this.sendRequest(`turn/interrupt`,{threadId:this.threadId,turnId:e})}catch(t){throw this.turnInProgress&&this.activeTurnId===e&&(this.interruptIssuedTurnId=void 0),t}}}emitNativeRaw(e){this.emit({type:`native.raw`,source:`codex.app_server`,...e})}getPendingRequest(e){return this.pendingRequests.get(qD(e))}classifyThreadScopedMessage(e){return!e||this.threadId&&e===this.threadId?`handle`:this.hasPendingThreadBindingRequest()?`buffer`:`ignore`}extractThreadIdFromServerRequest(e){return Z(KD(e.params).threadId)}extractThreadIdFromNotification(e){let t=KD(e.params);return Z(t.threadId)||Z(KD(t.thread).id)}extractThreadIdFromResponse(e,t){if(this.isThreadBindingMethod(e))return Z(KD(KD(t).thread).id)}hasPendingThreadBindingRequest(){for(let e of this.pendingRequests.values())if(this.isThreadBindingMethod(e.method))return!0;return!1}isThreadBindingMethod(e){return e===`thread/start`||e===`thread/resume`}setThreadIdAndFlushBuffered(e){if(this.threadId=e,this.bufferedThreadScopedMessages.length===0)return;let t=this.bufferedThreadScopedMessages.splice(0);for(let n of t)n.threadId===e&&(this.emitNativeRaw({message:n.message}),n.kind===`serverRequest`?this.handleServerRequest(n.payload):this.handleNotification(n.payload))}shouldHandleThreadScopedMessage(e){return!!e&&e===this.threadId}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}log(e,t,n={}){if(!this.logger)return;let r={provider:this.provider,providerMode:this.providerMode,sessionId:this.id,threadId:this.threadId,activeTurnId:this.activeTurnId,model:this.activeModel??this.model,cwd:this.cwd,...n};if(e===`info`){this.logger.info?.(r,t);return}if(e===`warn`){this.logger.warn?.(r,t);return}this.logger.error?.(r,t)}recordIncomingAppServerActivity(e,t,n){this.recordAppServerActivity(tk({direction:`incoming`,message:e,payloadLength:t,responseMethod:n}))}recordOutgoingAppServerActivity(e,t){this.recordAppServerActivity(tk({direction:`outgoing`,message:e,payloadLength:t}))}recordAppServerActivity(e){this.recentAppServerActivity.push(e),this.recentAppServerActivity.length>YO&&this.recentAppServerActivity.splice(0,this.recentAppServerActivity.length-YO)}};function ek(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function tk(e){let t=Z(e.message.method),n=Object.prototype.hasOwnProperty.call(e.message,`id`),r=KD(e.message.error),i=rk(t,t?e.message.params:e.message.error??e.message.result);return{at:new Date().toISOString(),direction:e.direction,messageKind:nk(t,n,e.direction),method:t,requestId:n?qD(e.message.id):void 0,requestMethod:e.responseMethod,threadId:i.threadId,turnId:i.turnId,itemId:i.itemId,payloadLength:e.payloadLength,deltaLength:i.deltaLength,preview:i.preview??ak(Z(r.message))}}function nk(e,t,n){return e&&t?n===`incoming`?`server_request`:`request`:e?`notification`:`response`}function rk(e,t){let n=KD(t),r=KD(n.thread),i=KD(n.turn),a=KD(n.item),o=Z(n.delta)??Z(n.text),s=ik(e,n,o);return{threadId:Z(n.threadId)??Z(r.id),turnId:Z(n.turnId)??Z(i.id),itemId:Z(n.itemId)??Z(a.id),deltaLength:typeof o==`string`?o.length:void 0,preview:ak(s)}}function ik(e,t,n){if(e===`item/commandExecution/outputDelta`||e===`item/fileChange/outputDelta`||e===`item/agentMessage/delta`||e===`item/plan/delta`||e===`item/reasoning/summaryTextDelta`||e===`item/reasoning/textDelta`)return n;if(e===`error`)return Z(KD(t.error).message)??Z(t.message)}function ak(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t.length<=XO?t:`${t.slice(0,XO)}...`}function ok(e){let t=/WebSocket closed \((\d+)\)/.exec(e);if(!t)return;let n=Number.parseInt(t[1]??``,10);return Number.isFinite(n)?n:void 0}function sk(e){return/WebSocket closed \(\d+\): (.+)$/.exec(e)?.[1]}function ck(e){return e?e===`max`?`xhigh`:e:null}function lk(e,t,n){if(e===`plan`){if(!t)throw Error(`Codex plan mode requires a resolved model.`);return{mode:`plan`,settings:{model:t,reasoning_effort:n,developer_instructions:null}}}}function uk(e,t){return{approvalPolicy:e.approvalPolicy??null,sandboxPolicy:t}}function dk(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function fk(e){let t=KD(e),n=Z(t.id),r=Z(t.header),i=Z(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=KD(e),n=Z(t.label),r=Z(t.description)??n,i=Z(t.markdown);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;return{id:n,header:r,question:i,multiSelect:t.multiSelect===!0,isOther:!!t.isOther,isSecret:!!t.isSecret,options:o}}function pk(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Array.from(new Set(t.map(e=>e.trim()).filter(Boolean)))]))}var mk=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new VD(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await xO()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=e.codexAppServerTransport===`stdio`?this.runtime.createNativeSession??RO.create:this.runtime.createWebSocketNativeSession??$O.create;try{return await t(e)}catch(t){if(this.requireNative)throw t;return console.warn(`[provider-adapters] codex native fallback to mock: ${String(t)}`),this.mockAdapter.createSession(e)}}};async function hk(e,t){let n=[],r=null,i=xk(t?.maxThreads),a=t?.sortKey,o=t?.updatedAfterUnixSeconds;do{let t=i===null?100:Math.max(0,i-n.length);if(t===0)break;let s=await gk({cwd:e,archived:!1,cursor:r,limit:i===null?100:Math.min(100,t),sortKey:a}),c=!1;for(let t of s.threads)if(t.cwd===e){if(o!==void 0&&t.updatedAt<o){if(a===`updated_at`){c=!0;break}continue}if(n.push(t),i!==null&&n.length>=i){c=!0;break}}if(c)break;r=s.nextCursor}while(r);return n}async function gk(e){return bO(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>bk(e)),nextCursor:n.nextCursor}})}async function _k(e,t=!0){return bO(async n=>bk((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function vk(e){return bO(async t=>{let n=!1;try{let r=await OO(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,await wk(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function yk(){let e=[],t=null;do{let n=await bO(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>Ck(e))),t=n.nextCursor}while(t);return e}function bk(e){let t=Z(KD(e).model)?.trim()||void 0;return{id:e.id,name:e.name??void 0,preview:e.preview,model:t,modelProvider:e.modelProvider,createdAt:e.createdAt,updatedAt:e.updatedAt,status:Sk(e.status),path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:Ek(e.source),gitInfo:e.gitInfo?KD(WD(e.gitInfo)):null,turns:e.turns.map(e=>Tk(e))}}function xk(e){return e===void 0||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}function Sk(e){let t=Z(KD(e).type);switch(t){case`active`:case`idle`:case`notLoaded`:case`systemError`:return t;default:return`idle`}}function Ck(e){return{id:e.id,model:e.model,displayName:e.displayName,description:e.description,isDefault:e.isDefault,defaultReasoningEffort:e.defaultReasoningEffort??void 0,supportedReasoningEfforts:(e.supportedReasoningEfforts??[]).map(e=>e.reasoningEffort)}}async function wk(e){let t=new Date(e.thread.updatedAt*1e3).toISOString();return kk({model:Dk(e.model),reasoningEffort:Ok(e.reasoningEffort),approvalPolicy:null,sandboxMode:null,updatedAt:t})}function Tk(e){return{id:e.id,status:e.status,error:e.error?KD(WD(e.error)):null,items:e.items.map(e=>HD(e))}}function Ek(e){if(typeof e==`string`)return e;if(typeof e==`object`&&e){let[t,n]=Object.entries(e)[0]??[];return t?typeof n==`string`&&n?`${t}:${n}`:t:`unknown`}return`unknown`}function Dk(e){return Z(e)?.trim()||void 0}function Ok(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function kk(e){let t=e.approvalPolicy!==null||e.sandboxMode!==null;return e.model||e.reasoningEffort!==null||t?{model:e.model,sessionTurnConfig:{mode:`default`,model:e.model??null,reasoningEffort:e.reasoningEffort,...t?{execution:{codex:{approvalPolicy:e.approvalPolicy,sandboxMode:e.sandboxMode}}}:{}},sessionTurnConfigUpdatedAt:e.updatedAt??``}:null}var Ak=5e3,jk=`Request interrupted by user`;function Mk(e){if((e.attachments?.length??0)===0)return e.text;let t=Nk(e);return(async function*(){yield{type:`user`,message:{role:`user`,content:t},parent_tool_use_id:null}})()}function Nk(e){let t=[];e.text.trim().length>0&&t.push({type:`text`,text:e.text});for(let n of e.attachments??[])if(n.kind===`image`){if(!n.dataBase64)throw Error(`Claude image input requires base64 attachment data`);t.push({type:`image`,source:{type:`base64`,media_type:n.mimeType,data:n.dataBase64}})}if(t.length===0)throw Error(`Claude turn input requires text or image attachments`);return t}function Pk(e){let t=[];e.text.trim().length>0&&t.push({type:`text`,text:e.text});for(let n of e.attachments??[])t.push({type:`image`,source:n.localPath?{type:`local_file`,path:n.localPath}:{type:`base64`,media_type:n.mimeType},remote_agent_attachment:Fk(n)});return t}function Fk(e){return{id:e.id,kind:e.kind,mimeType:e.mimeType,fileName:e.fileName,width:e.width,height:e.height,sizeBytes:e.sizeBytes,...e.localPath?{locator:{kind:`absolute`,path:e.localPath}}:{}}}var Ik=class{constructor(e,t,n,r,i){this.createQuery=n,this.id=e,this.model=t,this.activeModel=t,this.activeSessionConfig={},this.resumeSessionId=r,this.cwd=i?.cwd}id;provider=`claude`;providerMode=`native`;model;listeners=new Set;cwd;closed=!1;turnInProgress=!1;turnSequence=0;activeTurnId=null;activeAssistantItemId=null;assistantStarted=!1;assistantCompleted=!1;activeToolItemId=null;toolStarted=!1;activeQuery=null;activeAbortController=null;resumeSessionId;threadStartedEmitted=!1;activeModel;activeSessionConfig;interruptRequested=!1;pendingToolPermissionRequests=new Map;pendingUserInputRequests=new Map;pendingClaudeToolUses=new Map;activeTurnStarted=!1;activeTurnTerminalEmitted=!1;closePromise=null;interruptFallbackTimer=null;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getNativeSessionId(){return this.resumeSessionId}async sendInput(e,t){if(this.ensureOpen(),this.turnInProgress)throw Error(`A turn is already in progress`);this.turnInProgress=!0,this.turnSequence+=1,this.activeTurnId=`claude_turn_${this.turnSequence}`,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.pendingClaudeToolUses.clear(),this.interruptRequested=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1,this.clearInterruptFallbackTimer(),this.activeModel=t?.model??this.activeModel,this.activeSessionConfig=AO(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=LD(e),r=new AbortController,i=this.createQuery({prompt:Mk(n),model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:r,canUseTool:this.handleCanUseTool});this.activeAbortController=r,this.activeQuery=i,this.emitSyntheticUserInputEvents(n),this.startQueryLoop(i)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0;let e=this.activeQuery,t=this.activeAbortController;if(!e)return;let n=!1;if(typeof e.interrupt==`function`)try{await e.interrupt(),n=!0}catch{}if(n){this.armInterruptFallback(e,t);return}typeof e.close==`function`&&e.close(),t?.abort()}async close(){if(this.closePromise)return this.closePromise;this.closePromise=this.closeInternal(),await this.closePromise}async respondToolPermission(e,t,n){let r=this.pendingToolPermissionRequests.get(e);if(!r)throw Error(`Unknown tool approval request: ${e}`);this.pendingToolPermissionRequests.delete(e),t===`allow`?r.resolve({behavior:`allow`,updatedInput:r.input}):r.resolve({behavior:`deny`,message:n?.trim()||`Permission denied`}),this.emit({type:`tool.permission.resolved`,requestId:e,decision:t,reason:n,toolName:r.toolName,itemId:r.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`})}async respondUserInput(e,t){let n=this.pendingUserInputRequests.get(e);if(!n)throw Error(`Unknown user input request: ${e}`);this.pendingUserInputRequests.delete(e);let r=Vk(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:jO(r),tool_name:n.toolName,itemId:n.toolUseID,turn_id:n.turnId,questions:n.questions,answers:r,source_event_type:`can_use_tool`})}startQueryLoop(e){(async()=>{let t=null;try{for await(let t of e){if(this.closed||this.activeQuery!==e)return;let n=cA(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:lA(n.type),message:t});let r=this.mapClaudeMessage(t);for(let e of r)this.emit(e)}}catch(n){if(this.closed||this.activeQuery!==e)return;let r=n instanceof Error?n.message:String(n);this.interruptRequested?t=r:this.emit({type:`error`,message:r})}finally{if(this.closed||this.activeQuery!==e)return;if(this.clearInterruptFallbackTimer(),this.interruptRequested&&!this.activeTurnTerminalEmitted){let e=this.buildInterruptedTerminalEvents(t??jk);for(let t of e)this.emit(t)}this.turnInProgress=!1,this.interruptRequested=!1,this.activeQuery=null,this.activeAbortController=null,this.expirePendingToolPermissionRequests(`Turn finished`),this.expirePendingUserInputRequests(`Turn finished`),this.clearTurnState()}})()}async closeInternal(){if(this.closed)return;this.closed=!0,this.interruptRequested=!0,this.clearInterruptFallbackTimer();let e=this.activeAbortController;this.activeAbortController=null;let t=this.activeQuery;if(this.activeQuery=null,!this.activeTurnTerminalEmitted&&typeof t?.interrupt==`function`)try{await t.interrupt()}catch{}typeof t?.close==`function`&&t.close(),e?.abort(),this.turnInProgress=!1,this.clearTurnState(),this.expirePendingToolPermissionRequests(`Session closed`),this.expirePendingUserInputRequests(`Session closed`)}handleCanUseTool=async(e,t,n)=>Rk(e,t)?this.requestUserInput(e,t,n):Lk(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${nT(8)}`;return this.emit({type:`tool.permission.requested`,requestId:r,toolName:e,reason:n.decisionReason,blockedPath:n.blockedPath,suggestions:n.suggestions,agentId:n.agentID,itemId:n.toolUseID,turn_id:this.activeTurnId,source_event_type:`can_use_tool`}),new Promise((i,a)=>{if(n.signal.aborted){i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e,itemId:n.toolUseID,source_event_type:`abort`});return}let o=()=>{n.signal.removeEventListener(`abort`,o);let e=this.pendingToolPermissionRequests.get(r);e&&(this.pendingToolPermissionRequests.delete(r),i({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:r,decision:`deny`,reason:`Operation aborted`,toolName:e.toolName,itemId:e.toolUseID,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,o,{once:!0}),this.pendingToolPermissionRequests.set(r,{toolName:e,toolUseID:n.toolUseID,input:t,resolve:e=>{n.signal.removeEventListener(`abort`,o),i(e)},reject:e=>{n.signal.removeEventListener(`abort`,o),a(e)}})})}requestUserInput(e,t,n){let r=zk(t),i=`req_${nT(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,itemId:n.toolUseID,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((a,o)=>{if(n.signal.aborted){a({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emitUserInputResolved(i,{toolName:e,toolUseID:n.toolUseID,turnId:this.activeTurnId,input:t,questions:r},`interrupted`,`Operation aborted`,`abort`);return}let s=()=>{n.signal.removeEventListener(`abort`,s);let e=this.pendingUserInputRequests.get(i);e&&(this.pendingUserInputRequests.delete(i),a({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emitUserInputResolved(i,e,`interrupted`,`Operation aborted`,`abort`))};n.signal.addEventListener(`abort`,s,{once:!0}),this.pendingUserInputRequests.set(i,{toolName:e,toolUseID:n.toolUseID,turnId:this.activeTurnId,input:t,questions:r,resolve:e=>{n.signal.removeEventListener(`abort`,s),a(e)},reject:e=>{n.signal.removeEventListener(`abort`,s),o(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries()){n.resolve({behavior:`deny`,message:e,interrupt:!0});let r=e===`Turn finished`?`turn_finished`:`session_end`,i=e===`Turn finished`?`expired`:`cancelled`;this.emitUserInputResolved(t,n,i,e,r)}this.pendingUserInputRequests.clear()}emitUserInputResolved(e,t,n,r,i){this.emit({type:`user.input.resolved`,requestId:e,status:n,answeredCount:0,reason:r,tool_name:t.toolName,itemId:t.toolUseID,turn_id:t.turnId,questions:t.questions,source_event_type:i})}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1}armInterruptFallback(e,t){this.clearInterruptFallbackTimer(),this.interruptFallbackTimer=setTimeout(()=>{this.closed||!this.turnInProgress||!this.interruptRequested||this.activeQuery!==e||(e.close?.(),t?.abort())},Ak)}clearInterruptFallbackTimer(){this.interruptFallbackTimer&&=(clearTimeout(this.interruptFallbackTimer),null)}captureResumeSessionId(e){let t=cA(e),n=lA(t.session_id)??lA(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.text.trim()&&(e.attachments?.length??0)===0)return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${nT(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:Pk(e)},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=pA(e);if(t)return this.activeAssistantItemId=t,t;if(this.activeAssistantItemId)return this.activeAssistantItemId;let n=this.activeTurnId?`claude_assistant_${this.activeTurnId}`:`claude_assistant_${Date.now()}`;return this.activeAssistantItemId=n,n}ensureToolItemId(e){let t=lA(e.tool_id)??lA(e.tool_use_id)??dA(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=lA(e.uuid);if(n)return this.activeToolItemId=n,n;let r=mA(lA(e.tool_name)??`tool`),i=this.activeTurnId?`claude_tool_${this.activeTurnId}_${r}`:`claude_tool_${r}_${Date.now()}`;return this.activeToolItemId=i,i}buildAssistantCompletionTailEvent(){if(!this.assistantStarted||this.assistantCompleted)return[];let e=this.activeAssistantItemId;return e?(this.assistantCompleted=!0,[{type:`item.completed`,item:{id:e,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_end`}}]):[]}buildInterruptedTerminalEvents(e){return this.activeTurnTerminalEmitted=!0,[...this.buildAssistantCompletionTailEvent(),{type:`turn.failed`,status:`interrupted`,error:{message:e},turn_id:this.activeTurnId,source_event_type:`abort`}]}mapClaudeMessage(e){let t=cA(e),n=lA(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!tA(t))return[];let n=cA(t.message),r=nA(n),i=rA(n);return!r&&i.length===0?[]:[{type:`item.completed`,item:{id:lA(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,...r?{text:r}:{},...i.length>0?{attachments:i}:{},turn_id:this.activeTurnId,source_event_type:lA(t.source_event_type)??`user`}}]}if(n===`assistant`){let e=this.mapStructuredClaudeToolUse(t);if(e.length>0)return e;let n=this.activeAssistantItemId,r=this.ensureAssistantItemId(t);n&&n!==r&&(this.assistantStarted=!1,this.assistantCompleted=!1);let i=eA(t),a=[...this.maybeEmitTurnStarted(`assistant`)];return this.assistantStarted||=(a.push({type:`item.started`,item:{id:r,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`assistant`}}),!0),a.push({type:`item.completed`,item:{id:r,type:`agent_message`,text:i,turn_id:this.activeTurnId,source_event_type:`assistant`}}),this.assistantCompleted=!0,a}if(n===`stream_event`){let e=cA(t.event);if(lA(e.type)===`message_start`){let t=pA(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=iA(t);if(!n)return[];let r=this.activeAssistantItemId,i=this.ensureAssistantItemId(t);r&&r!==i&&(this.assistantStarted=!1,this.assistantCompleted=!1);let a=[];return a.push(...this.maybeEmitTurnStarted(`stream_event`)),this.assistantStarted||=(a.push({type:`item.started`,item:{id:i,type:`agent_message`,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),!0),a.push({type:`item.updated`,item:{id:i,type:`agent_message`,text:n,turn_id:this.activeTurnId,source_event_type:`stream_event`}}),a}if(n===`result`){let e=this.maybeEmitTurnStarted(`result`);if(t.is_error===!0||lA(t.subtype)?.startsWith(`error_`)===!0){let n=oA(t,this.interruptRequested),r=aA(t,n);return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.failed`,...n?{status:`interrupted`}:{},error:{message:r},usage:sA(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:sA(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}if(n===`tool_use_summary`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=lA(t.summary)??`tool summary`,i=lA(t.tool_name)??`tool`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_use_summary`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:r,status:`running`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),a.push({type:`item.completed`,item:{id:n,type:`tool_status`,text:r,status:`completed`,tool_name:i,turn_id:this.activeTurnId,source_event_type:`tool_use_summary`}}),this.activeToolItemId=null,this.toolStarted=!1,a}if(n===`tool_progress`){let e=this.activeToolItemId,n=this.ensureToolItemId(t);e&&e!==n&&(this.toolStarted=!1);let r=lA(t.tool_name)??`tool`,i=lA(t.message)??`${r} running`,a=[];return a.push(...this.maybeEmitTurnStarted(`tool_progress`)),this.toolStarted||=(a.push({type:`item.started`,item:{id:n,type:`tool_status`,tool_name:r,status:`running`,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),!0),a.push({type:`item.updated`,item:{id:n,type:`tool_status`,text:i,status:`running`,tool_name:r,turn_id:this.activeTurnId,source_event_type:`tool_progress`}}),a}if(n===`system`){let e=lA(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(lA(t.session_id)??lA(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:lA(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=lA(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=Hk(e);if(t.length===0)return[];let n=[];n.push(...this.maybeEmitTurnStarted(`assistant.tool_use`));for(let e of t)this.pendingClaudeToolUses.set(e.id,e),n.push({type:`item.started`,item:{id:e.id,type:`tool_status`,turn_id:this.activeTurnId,tool_name:e.toolName,title:e.title,text:e.title,status:`running`,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,subagent_type:e.subagentType,description:e.description,file_path:e.filePath,source_event_type:`assistant.tool_use`}});return n}mapStructuredClaudeToolResult(e){let t=Uk(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=Wk({toolUse:n,toolUseId:t.toolUseId,isError:t.isError,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function Lk(e){return typeof e.decisionReason==`string`&&e.decisionReason.trim().length>0||typeof e.blockedPath==`string`&&e.blockedPath.trim().length>0?!0:Array.isArray(e.suggestions)&&e.suggestions.length>0}function Rk(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function zk(e){return(Array.isArray(e.questions)?e.questions:[{id:`question_1`,header:`Question`,question:typeof e.question==`string`?e.question:`Please provide input`,multiSelect:!1,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:e.options}]).map((e,t)=>{if(typeof e!=`object`||!e)return null;let n=e,r=typeof n.id==`string`&&n.id?n.id:`question_${t+1}`,i=typeof n.header==`string`&&n.header?n.header:`Question`,a=typeof n.question==`string`&&n.question?n.question:`Please provide input`,o=Bk(n.options);return{id:r,header:i,question:a,multiSelect:n.multiSelect===!0,isOther:n.isOther===!0,isSecret:n.isSecret===!0,options:o}}).filter(e=>e!==null)}function Bk(e){if(!Array.isArray(e))return null;let t=e.map(e=>{if(typeof e==`string`)return{label:e,description:e};if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.label==`string`?t.label:``,r=typeof t.description==`string`?t.description:n,i=typeof t.markdown==`string`&&t.markdown.length>0?t.markdown:void 0;return n?{label:n,description:r,markdown:i}:null}).filter(e=>e!==null);return t.length>0?t:null}function Vk(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function Hk(e){let t=cA(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=cA(e);if(t.type!==`tool_use`)continue;let n=lA(t.id),i=lA(t.name),a=cA(t.input);if(!(!n||!i)){if(i===`Task`){let e=lA(a.subagent_type),t=lA(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:lA(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=lA(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=lA(a.file_path);r.push({id:n,toolName:`Write`,title:Yk(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function Uk(e){let t=cA(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=cA(e);if(t.type!==`tool_result`)continue;let n=lA(t.tool_use_id);if(n)return{toolUseId:n,isError:t.is_error===!0}}return null}function Wk(e){let t=cA(e.raw.tool_use_result),n=Gk(t.content)??nA(cA(e.raw.message)),r=cA(t.usage),i=fA(t.totalTokens)??fA(r.total_tokens)??fA(r.output_tokens),a=fA(t.totalToolUseCount),o=fA(t.totalDurationMs),s=lA(t.agentId),c=lA(t.filePath)??e.toolUse.filePath,l=e.isError?`failed`:`completed`;if(e.toolUse.toolName===`Task`){let t=e.isError?`Failed`:qk(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:l,status_label:t,is_error:e.isError,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=Kk(t)??n,a=e.isError?`Failed`:`Done`;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:a,status:l,status_label:a,is_error:e.isError,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=uA(t.content),r=e.isError?`Failed`:Jk(Zk(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:l,status_label:r,is_error:e.isError,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function Gk(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=cA(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
|
|
517
517
|
`):void 0}function Kk(e){return uA(cA(e.file).content)||Gk(e.content)}function qk(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${Qk(t)} tokens`),typeof n==`number`&&r.push($k(n)),r.join(` · `)}function Jk(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function Yk(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${Xk(e)})`:`Write`}function Xk(e){let t=e.split(`/`);return t[t.length-1]||e}function Zk(e){if(e)return e.split(`
|
|
518
518
|
`).length}function Qk(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function $k(e){let t=Math.max(1,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}m`:`${n}m ${r}s`}function eA(e){return nA(cA(e.message))||(uA(e.result)??``)}function tA(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=cA(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>cA(e).type===`tool_result`)}function nA(e){let t=uA(e.content);if(t)return t;let n=uA(e.text)??uA(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=cA(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
|
|
519
519
|
`)}function rA(e){let t=Array.isArray(e.content)?e.content:[],n=[];for(let e of t){let t=cA(e);if(t.type!==`image`)continue;let r=cA(t.remote_agent_attachment);if(Object.keys(r).length>0){n.push(r);continue}let i=cA(t.source),a=lA(i.media_type)??lA(i.mediaType),o=lA(i.path);n.push({id:lA(t.id)??o??`claude_image_${n.length+1}`,kind:`image`,mimeType:a,...o?{locator:{kind:`absolute`,path:o}}:{}})}return n}function iA(e){let t=cA(cA(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function aA(e,t=!1){if(t)return jk;let n=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return n.length>0?n.join(`; `):lA(e.subtype)||`Claude turn failed`}function oA(e,t){return t||(lA(e.terminal_reason)??lA(e.terminalReason))===`aborted_streaming`?!0:(Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[]).some(e=>e.includes(`result_type=user`)||e.includes(`[Request interrupted by user]`)||e.includes(`[Request interrupted by user for tool use]`))}function sA(e){let t=cA(e);return{input_tokens:fA(t.input_tokens)??fA(t.inputTokens)??0,cached_input_tokens:fA(t.cached_input_tokens)??fA(t.cache_read_input_tokens)??fA(t.cacheReadInputTokens)??0,output_tokens:fA(t.output_tokens)??fA(t.outputTokens)??0}}function cA(e){return typeof e==`object`&&e?e:{}}function lA(e){if(typeof e==`string`&&e.trim())return e}function uA(e){if(typeof e==`string`&&e.length>0)return e}function dA(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function fA(e){if(typeof e==`number`&&Number.isFinite(e))return e}function pA(e){let t=lA(cA(e.message).id);if(t)return t;let n=lA(cA(cA(e.event).message).id);if(n)return n}function mA(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var hA=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){let n=LD(e);if((n.attachments?.length??0)>0)throw Error(`Native legacy session does not support image attachments`);let r=n.text;if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(r);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(r);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:r});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=gA(e);for(let e of this.listeners)e(t)};if(typeof e?.subscribe==`function`){let n=e.subscribe(e=>t(e));typeof n==`function`&&(this.unsubscribe=n);return}if(typeof e?.on==`function`){let n=e=>t(e);e.on(`event`,n),this.unsubscribe=()=>{typeof e?.off==`function`&&e.off(`event`,n)};return}throw Error(`Native session does not expose a known event subscription API`)}};function gA(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var _A=`@anthropic-ai/claude-agent-sdk`,vA=`claude-sonnet-4-6`,yA=1e4,bA=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(_A),!0}catch{return!1}}async createSession(e){if(!this.preferNative)throw Error(`Claude native provider is disabled. Set ENABLE_NATIVE_PROVIDERS=true to use Claude sessions.`);try{let t=await import(_A),n=await xA(SA(t,e),yA,`Claude native query session creation timed out`);if(n)return n;let r=await xA(CA(t,e),yA,`Claude legacy native session creation timed out`);if(r)return r;throw this.requireNative,Error(`Claude SDK loaded but no supported stable session API was found`)}catch(e){throw Error(`Claude native session creation failed: ${String(e)}`)}}};async function xA(e,t,n){if(!Number.isFinite(t)||t<=0)return e;let r,i=new Promise((e,i)=>{r=setTimeout(()=>{i(Error(n))},t)});try{return await Promise.race([e,i])}finally{r&&clearTimeout(r)}}async function SA(e,t){let n=wA(e);if(!n)return null;let r=t.model??vA;return new Ik(t.sessionId,r,({prompt:e,model:i,sessionConfig:a,resume:o,abortController:s,canUseTool:c})=>{let l=a?.permissionMode??t.sessionConfig?.permissionMode??`default`,u={model:i??r,includePartialMessages:!0,abortController:s,canUseTool:c,permissionMode:l},d=TA(a?.reasoningEffort??t.sessionConfig?.reasoningEffort);return d&&(u.effort=d),l===`bypassPermissions`&&(u.allowDangerouslySkipPermissions=!0),t.cwd&&(u.cwd=t.cwd),o&&(u.resume=o,u.forkSession=!1),n({prompt:e,options:u})},t.resumeSessionId,{cwd:t.cwd})}async function CA(e,t){if(typeof e?.createSession==`function`){let n=await e.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new hA(`claude`,t.sessionId,t.model,n)}if(typeof e?.ClaudeAgentClient==`function`){let n=new e.ClaudeAgentClient;if(typeof n?.createSession==`function`){let e=await n.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new hA(`claude`,t.sessionId,t.model,e)}}if(typeof e?.default?.createSession==`function`){let n=await e.default.createSession({model:t.model,cwd:t.cwd,metadata:t.metadata,sessionId:t.sessionId});return new hA(`claude`,t.sessionId,t.model,n)}return null}function wA(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function TA(e){if(e){if(e===`max`)return`max`;if(e===`high`||e===`medium`||e===`low`)return e;if(e===`xhigh`)return`max`;if(e===`minimal`||e===`none`)return`low`}}function EA(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new mk(n,r):new bA(n,r)}const DA=p.default.join(`.claude`,`projects`),OA=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function kA(e){return(await(0,O.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>IA(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function AA(e,t){let n=PA(e,t?.homeDir),r=p.default.resolve(e);try{let i=await LA(e,n,r,{maxSessions:mj(t?.maxSessions),updatedAfterMs:pj(t?.updatedAfterMs)});if(i.length>0)return i}catch{}return RA(n,{maxSessions:mj(t?.maxSessions),updatedAfterMs:pj(t?.updatedAfterMs)})}async function jA(e){let t=await $A(e.nativeSessionId,e.projectPath),n=await ej(e.projectPath,e.nativeSessionId,e.homeDir),r=VA(t,{createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),i=WA(r.updatedAt,n.mtimeMs),a=HA(r.model);return{rawEvents:MA({rows:t,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,nativeSessionId:e.nativeSessionId,createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),model:r.model,sessionTurnConfig:a,sessionTurnConfigUpdatedAt:a?i:void 0,updatedAt:i,status:GA(t),nativeWatchPath:NA(e.projectPath,e.nativeSessionId,e.homeDir)}}function MA(e){let t=[],n=VA(e.rows,{createdAtFallbackMs:e.createdAtFallbackMs,updatedAtFallbackMs:e.updatedAtFallbackMs}),r=Date.parse(n.createdAt),i=0,a=Number.isFinite(r)?r:0,o=e=>{if(e){let t=Date.parse(e);if(Number.isFinite(t))return a=Math.max(a+1,t),new Date(t).toISOString()}return a+=1,new Date(a).toISOString()};for(let n of e.rows)n.type!==`system`&&(i+=1,t.push({v:`1.0`,kind:`provider.raw`,rawSeq:i,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:`raw_hist_claude_${e.sessionId}_${i.toString().padStart(6,`0`)}`,ts:o(n.timestamp),type:`native.raw`,payload:{raw:{source:`claude.history.getSessionMessages`,native_type:n.type??`unknown`,message:n.raw,historyReplay:!0,replaySynthetic:!1,source_line:n.line,native_session_id:e.nativeSessionId}}}));return t}function NA(e,t,n){return p.default.join(PA(e,n),`${t}.jsonl`)}function PA(e,t){let n=t??f.default.homedir();return p.default.join(n,DA,FA(e))}function FA(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function IA(e){let t=lj(e.customTitle)??lj(e.summary)??lj(e.firstPrompt),n=ZA(e.createdAt??e.lastModified),r=ZA(e.lastModified);return{nativeSessionId:e.sessionId,cwd:XA(e.cwd),title:t,createdAt:n,updatedAt:r,status:`idle`}}async function LA(e,t,n,r){let i=Math.max(1,Math.min(r.maxSessions??100,100)),a=[],o=0,s=!1;for(;r.maxSessions===void 0||a.length<r.maxSessions;){let c=r.maxSessions===void 0?i:Math.max(1,Math.min(i,r.maxSessions-a.length)),l=await(0,O.listSessions)({dir:e,limit:c,offset:o});if(l.length===0)break;for(let e of l){let i=pj(e.lastModified);if(r.updatedAfterMs!==void 0&&i!==void 0&&i<r.updatedAfterMs){s=!0;break}let o=IA(e);if(typeof o.cwd!=`string`||p.default.resolve(o.cwd)!==n)continue;let c=await zA(t,{nativeSessionId:o.nativeSessionId,sdkSession:o});if(c&&(a.push(c),r.maxSessions!==void 0&&a.length>=r.maxSessions))break}if(s||r.maxSessions!==void 0&&a.length>=r.maxSessions||l.length<c)break;o+=l.length}return BA(a,r)}async function RA(e,t){let n=[];try{n=await d.default.readdir(e,{withFileTypes:!0})}catch(e){if(e.code!==`ENOENT`)throw e}let r=[];for(let t of n){if(!t.isFile()||!t.name.endsWith(`.jsonl`))continue;let n=await zA(e,{nativeSessionId:t.name.slice(0,-6)});n&&r.push(n)}return BA(r,t)}async function zA(e,t){let n=p.default.join(e,`${t.nativeSessionId}.jsonl`),r;try{r=await QA(n)}catch(e){if(e.code===`ENOENT`)return t.sdkSession;throw e}if(!YA(r))return;let i=await d.default.stat(n),a=t.sdkSession?.createdAt?fj(t.sdkSession.createdAt):void 0,o=t.sdkSession?.updatedAt?fj(t.sdkSession.updatedAt):void 0,s=VA(r,{createdAtFallbackMs:a??i.birthtimeMs,updatedAtFallbackMs:o??i.mtimeMs});return{nativeSessionId:t.nativeSessionId,model:s.model,title:t.sdkSession?.title??s.title,createdAt:s.createdAt,updatedAt:t.sdkSession?.updatedAt??s.updatedAt,status:GA(r)}}function BA(e,t){let n=e.filter(e=>{if(t.updatedAfterMs===void 0)return!0;let n=fj(e.updatedAt);return n===void 0?!0:n>=t.updatedAfterMs}).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt));return t.maxSessions===void 0?n:n.slice(0,t.maxSessions)}function VA(e,t){let n,r,i,a;for(let t of e){t.timestampMs!==void 0&&(i=i===void 0?t.timestampMs:Math.min(i,t.timestampMs),a=a===void 0?t.timestampMs:Math.max(a,t.timestampMs)),!r&&t.type===`user`&&(r=oj(ij(sj(t.raw.message))));let e=UA(t);e&&(n=e)}let o=i??pj(t.createdAtFallbackMs)??0,s=a??pj(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function HA(e){let t=XA(e);if(t)return{mode:`default`,model:t,reasoningEffort:null}}function UA(e){return XA(sj(e.raw.message).model)??XA(e.raw.model)}function WA(e,t){let n=fj(e)??0,r=pj(t)??0;return new Date(Math.max(n,r)).toISOString()}function GA(e,t=Date.now()){let n=null;for(let t of e){let e=KA(t);e&&(n=e)}return!n?.unresolved||n.timestampMs!==void 0&&t-n.timestampMs>6e5?`idle`:`running`}function KA(e){let t=e.timestampMs??fj(e.timestamp??``);switch(e.type){case`assistant`:case`result`:case`tool_use_summary`:return{unresolved:!1,timestampMs:t};case`stream_event`:case`tool_progress`:return{unresolved:!0,timestampMs:t};case`user`:return qA(e.raw,t);default:return null}}function qA(e,t){let n=sj(e);if(n.isMeta===!0)return null;let r=sj(n.message);if(rj(r).length>0)return{unresolved:!0,timestampMs:t};let i=ij(r);return i?JA(i)?{unresolved:!1,timestampMs:t}:{unresolved:!0,timestampMs:t}:null}function JA(e){let t=e.toLowerCase();return t.includes(`[request interrupted by user]`)||t.includes(`[request interrupted by user for tool use]`)?!0:t.includes(`<command-name>/exit</command-name>`)||t.includes(`<command-message>exit</command-message>`)||t.includes(`<local-command-stdout>catch you later!</local-command-stdout>`)}function YA(e){for(let t of e){if(t.type===`user`){let e=sj(t.raw.message);if(ij(e)||rj(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=sj(t.raw.message);if(ij(e)||nj(e).length>0||cj(t.raw.error))return!0}return!1}function XA(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function ZA(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function QA(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|