craby-gateway 0.27.3 → 0.27.5
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 +2 -2
- package/package.json +2 -2
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.27.3`,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.92`,"@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.27.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(`
|
|
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
|
`)?`
|
|
@@ -512,7 +512,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
512
512
|
`)}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(`
|
|
513
513
|
`);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)}}},KD=3,qD=250;function JD(e){return e instanceof Error?/thread .* is closing; retry thread\/resume after the thread is closed/i.test(e.message):!1}async function YD(e,t){let n=Math.max(1,t?.maxAttempts??KD),r=Math.max(0,t?.retryDelayMs??qD),i;for(let t=1;t<=n;t+=1)try{return await e()}catch(e){if(i=e,!JD(e)||t>=n)throw e;r>0&&await XD(r)}throw i instanceof Error?i:Error(`Codex thread resume retry failed`)}function XD(e){return new Promise(t=>{setTimeout(t,e)})}function ZD(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 QD(e){let t=0;for(let n of Object.values(e))n.some(e=>e.trim().length>0)&&(t+=1);return t}var $D=3e4,eO=1e3,tO=2e3,nO=1e3,rO={name:`remote-agent-desktop-gateway`,title:`Remote Agent Desktop Gateway`,version:`0.1.0`},iO=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;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?.()??aO(),n.requestTimeoutMs??$D,n.closeInterruptTimeoutMs??eO,n.closeGraceTimeoutMs??tO,n.forceKillTimeoutMs??nO);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=ZD(this.activeSessionConfig,t?.sessionConfig);if(this.hasThreadOverrideChanges(n,r)){let e=await this.resumeThread(this.threadId,{model:n,sessionConfig:r});e&&(this.threadId=e)}this.activeModel=n,this.activeSessionConfig=r;let i=[{type:`text`,text:e,text_elements:[]}],a=sO(this.activeSessionConfig.reasoningEffort),o,s=cO(t?.mode,n,a);try{o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:a,collaborationMode:s})}catch(e){if(!(a===`minimal`&&lO(e)))throw e;this.emit({type:`status.progress`,message:`Retrying turn/start with reasoning effort 'low' because 'minimal' is incompatible with web_search.`,originalMethod:`turn/start`,params:{requested_effort:a,retry_effort:`low`}}),o=await this.sendRequest(`turn/start`,{threadId:this.threadId,input:i,effort:`low`,collaborationMode:cO(t?.mode,n,`low`)})}let c=pD(o.turn?.id);c&&(this.activeTurnId=c),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=dO(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:QD(r),inputMethod:n.method})}async bootstrap(){let e={clientInfo:rO,capabilities:{experimentalApi:!0,optOutNotificationMethods:hD}};await this.sendRequest(`initialize`,e),this.sendNotification(`initialized`);let t=await this.sendRequest(`account/read`,{refreshToken:!1});if(t.requiresOpenaiAuth&&t.account===null)throw Error("Codex app-server requires OpenAI authentication. Please sign in with `codex` on this machine first.");let n=this.resumeSessionId?await this.resumeThread(this.resumeSessionId):await this.startThread();if(!n)throw Error(`Codex app-server did not return a thread id`);this.threadId=n}async startThread(){let e={model:this.activeModel??null,cwd:this.cwd??null,approvalPolicy:this.activeSessionConfig.approvalPolicy??null,sandbox:this.activeSessionConfig.sandboxMode??null,experimentalRawEvents:!1,persistExtendedHistory:!1};return pD((await this.sendRequest(`thread/start`,e)).thread?.id)}async resumeThread(e,t){let n=t?.model??this.activeModel,r=t?.sessionConfig??this.activeSessionConfig,i={threadId:e,model:n??null,cwd:this.cwd??null,approvalPolicy:r.approvalPolicy??null,sandbox:r.sandboxMode??null,persistExtendedHistory:!1};return pD((await YD(()=>this.sendRequest(`thread/resume`,i))).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 fO(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
514
|
`);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=pD(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=mD(e.id),n=this.pendingRequests.get(t);if(n){if(this.pendingRequests.delete(t),clearTimeout(n.timeoutId),e.error!==void 0){let t=fD(e.error),r=pD(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_${Cw(8)}`;this.pendingApprovals.set(i,{rpcId:e,method:t,kind:n});let a=fD(r),o=pD(a.threadId);o&&(this.threadId=o),this.emit({type:`tool.permission.requested`,requestId:i,toolName:n===`command`?`command_execution`:`file_change`,reason:pD(a.reason),threadId:o,turnId:pD(a.turnId),itemId:pD(a.itemId),approvalMethod:t,rawParams:uD(a)})}registerUserInputRequest(e,t,n){let r=`req_${Cw(8)}`;this.pendingUserInputs.set(r,{rpcId:e,method:t});let i=pD(n.threadId);i&&(this.threadId=i);let a=Array.isArray(n.questions)?n.questions.map(uO).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:uD(n)})}handleNotification(e){let t=(e,t)=>{let n=fD(fD(e).turn),r=pD(n.status)??t;if(this.turnInProgress=!1,this.activeTurnId=void 0,this.resetInterruptState(),r===`failed`){this.emit({type:`turn.failed`,status:r,turn:uD(n),error:uD(n.error??{})});return}this.emit({type:`turn.completed`,status:r,turn:uD(n)})};if(e.method===`turn/interrupted`){t(e.params,`interrupted`);return}switch(e.method){case`thread/started`:{let t=e.params,n=pD(t.thread?.id);n&&(this.threadId=n),this.emitThreadTitleUpdated(pD(t.thread?.preview),`codex.thread_preview`,{thread_id:n??this.threadId}),this.emit({type:`thread.started`,thread_id:n,thread:uD(t.thread)});return}case`thread/name/updated`:{let t=e.params,n=pD(t.threadId);n&&(this.threadId=n),this.emitThreadTitleUpdated(pD(t.threadName),`codex.thread_name_updated`,{thread_id:n??this.threadId});return}case`turn/started`:{let t=e.params,n=pD(t.turn?.id);n&&(this.activeTurnId=n),this.turnInProgress=!0,this.flushQueuedInterrupt(`turn_started_notification`),this.emit({type:`turn.started`,turn:uD(t.turn)});return}case`turn/completed`:t(e.params);return;case`item/started`:{let t=e.params;this.emit({type:`item.started`,thread_id:pD(t.threadId),turn_id:pD(t.turnId),item:cD(t.item)});return}case`item/completed`:{let t=e.params;this.emit({type:`item.completed`,thread_id:pD(t.threadId),turn_id:pD(t.turnId),item:cD(t.item)});return}case`item/agentMessage/delta`:{let t=e.params;this.emit({type:`item.updated`,thread_id:pD(t.threadId),turn_id:pD(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:pD(t.threadId),turn_id:pD(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:pD(t.threadId),turn_id:pD(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=fD(e.params);this.emit({type:`item.updated`,thread_id:pD(t.threadId),turn_id:pD(t.turnId),item:{id:pD(t.itemId),type:e.method.startsWith(`item/plan`)?`plan`:`reasoning`,text:pD(t.delta)??pD(t.text)??``,original_method:e.method,payload:uD(t)}});return}case`error`:{let t=e.params;this.emit({type:`error`,message:pD(t.error?.message)??`Codex app-server error`,error:uD(t.error),will_retry:t.willRetry===!0,thread_id:pD(t.threadId),turn_id:pD(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=mD(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)}
|
|
515
|
-
`)}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=oO(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 aO(){let e=TD();return(0,D.spawn)(e.command,[...e.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function oO(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function sO(e){return e?e===`max`?`xhigh`:e:null}function cO(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 lO(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function uO(e){let t=fD(e),n=pD(t.id),r=pD(t.header),i=pD(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=fD(e),n=pD(t.label),r=pD(t.description)??n,i=pD(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 dO(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 fO(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 pO=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new sD(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await HD()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??iO.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 mO(e,t){let n=[],r=null,i=bO(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 hO({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 hO(e){return VD(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>yO(e)),nextCursor:n.nextCursor}})}async function gO(e,t=!0){return VD(async n=>yO((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function _O(e){return VD(async t=>{let n=!1;try{let r=await YD(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,await CO(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function vO(){let e=[],t=null;do{let n=await VD(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>SO(e))),t=n.nextCursor}while(t);return e}function yO(e){let t=pD(fD(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:xO(e.status),path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:TO(e.source),gitInfo:e.gitInfo?fD(uD(e.gitInfo)):null,turns:e.turns.map(e=>wO(e))}}function bO(e){return e===void 0||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}function xO(e){let t=pD(fD(e).type);switch(t){case`active`:case`idle`:case`notLoaded`:case`systemError`:return t;default:return`idle`}}function SO(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 CO(e){let t=new Date(e.thread.updatedAt*1e3).toISOString();return OO({model:EO(e.model),reasoningEffort:DO(e.reasoningEffort),approvalPolicy:null,sandboxMode:null,updatedAt:t})}function wO(e){return{id:e.id,status:e.status,error:e.error?fD(uD(e.error)):null,items:e.items.map(e=>cD(e))}}function TO(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 EO(e){return pD(e)?.trim()||void 0}function DO(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function OO(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 kO=5e3,AO=`Request interrupted by user`,jO=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=ZD(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0;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=IO(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:QD(r),questions:PO(n.input),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=nk(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:rk(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??AO);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,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)=>NO(e,t)?this.requestUserInput(e,t,n):MO(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${Cw(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=PO(t),i=`req_${Cw(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1}armInterruptFallback(e,t){this.clearInterruptFallbackTimer(),this.interruptFallbackTimer=setTimeout(()=>{this.closed||!this.turnInProgress||!this.interruptRequested||this.activeQuery!==e||(e.close?.(),t?.abort())},kO)}clearInterruptFallbackTimer(){this.interruptFallbackTimer&&=(clearTimeout(this.interruptFallbackTimer),null)}captureResumeSessionId(e){let t=nk(e),n=rk(t.session_id)??rk(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${Cw(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=sk(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=rk(e.tool_id)??rk(e.tool_use_id)??ak(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=rk(e.uuid);if(n)return this.activeToolItemId=n,n;let r=ck(rk(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=nk(e),n=rk(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!XO(t))return[];let n=ZO(nk(t.message));return n?[{type:`item.completed`,item:{id:rk(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:rk(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=YO(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=nk(t.event);if(rk(e.type)===`message_start`){let t=sk(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=QO(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||rk(t.subtype)?.startsWith(`error_`)===!0){let n=ek(t,this.interruptRequested),r=$O(t,n);return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.failed`,...n?{status:`interrupted`}:{},error:{message:r},usage:tk(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:tk(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=rk(t.summary)??`tool summary`,i=rk(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=rk(t.tool_name)??`tool`,i=rk(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=rk(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(rk(t.session_id)??rk(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:rk(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=rk(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=LO(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=RO(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=zO({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function MO(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 NO(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function PO(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=FO(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 FO(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 IO(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function LO(e){let t=nk(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=nk(e);if(t.type!==`tool_use`)continue;let n=rk(t.id),i=rk(t.name),a=nk(t.input);if(!(!n||!i)){if(i===`Task`){let e=rk(a.subagent_type),t=rk(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:rk(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=rk(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=rk(a.file_path);r.push({id:n,toolName:`Write`,title:WO(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function RO(e){let t=nk(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=nk(e);if(t.type!==`tool_result`)continue;let n=rk(t.tool_use_id);if(n)return{toolUseId:n}}return null}function zO(e){let t=nk(e.raw.tool_use_result),n=BO(t.content)??ZO(nk(e.raw.message)),r=nk(t.usage),i=ok(t.totalTokens)??ok(r.total_tokens)??ok(r.output_tokens),a=ok(t.totalToolUseCount),o=ok(t.totalDurationMs),s=rk(t.agentId),c=rk(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=HO(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=VO(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=ik(t.content),r=UO(KO(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function BO(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=nk(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
|
|
515
|
+
`)}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=oO(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 aO(){let e=TD();return(0,D.spawn)(e.command,[...e.args,`app-server`,`--listen`,`stdio://`],{stdio:[`pipe`,`pipe`,`pipe`],windowsHide:!0})}function oO(e){if(typeof e!=`string`)return;let t=e.replace(/\s+/g,` `).trim();if(t)return t}function sO(e){return e?e===`max`?`xhigh`:e:null}function cO(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 lO(e){return e instanceof Error?/reasoning\.effort ['"]minimal['"]/i.test(e.message)&&/web_search/i.test(e.message):!1}function uO(e){let t=fD(e),n=pD(t.id),r=pD(t.header),i=pD(t.question),a=t.options;if(!n||!r||!i)return null;let o=Array.isArray(a)?a.map(e=>{let t=fD(e),n=pD(t.label),r=pD(t.description)??n,i=pD(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 dO(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 fO(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 pO=class{constructor(e,t,n={}){this.preferNative=e,this.requireNative=t,this.runtime=n}provider=`codex`;mockAdapter=new sD(`codex`);async isNativeAvailable(){try{return this.runtime.probeAvailability?await this.runtime.probeAvailability():await HD()}catch{return!1}}async createSession(e){if(this.requireNative&&!this.preferNative)throw Error(`Native Codex provider is required but ENABLE_NATIVE_PROVIDERS is disabled`);if(!this.preferNative)return this.mockAdapter.createSession(e);let t=this.runtime.createNativeSession??iO.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 mO(e,t){let n=[],r=null,i=bO(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 hO({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 hO(e){return VD(async t=>{let n=await t.sendRequest(`thread/list`,e);return{threads:n.data.map(e=>yO(e)),nextCursor:n.nextCursor}})}async function gO(e,t=!0){return VD(async n=>yO((await n.sendRequest(`thread/read`,{threadId:e,includeTurns:t})).thread))}async function _O(e){return VD(async t=>{let n=!1;try{let r=await YD(()=>t.sendRequest(`thread/resume`,{threadId:e,persistExtendedHistory:!1}));return n=!0,await CO(r)}finally{if(n)try{await t.sendRequest(`thread/unsubscribe`,{threadId:e})}catch{}}})}async function vO(){let e=[],t=null;do{let n=await VD(async e=>e.sendRequest(`model/list`,{cursor:t,limit:100}));e.push(...n.data.map(e=>SO(e))),t=n.nextCursor}while(t);return e}function yO(e){let t=pD(fD(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:xO(e.status),path:e.path,cwd:e.cwd,cliVersion:e.cliVersion,source:TO(e.source),gitInfo:e.gitInfo?fD(uD(e.gitInfo)):null,turns:e.turns.map(e=>wO(e))}}function bO(e){return e===void 0||!Number.isFinite(e)?null:Math.max(1,Math.trunc(e))}function xO(e){let t=pD(fD(e).type);switch(t){case`active`:case`idle`:case`notLoaded`:case`systemError`:return t;default:return`idle`}}function SO(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 CO(e){let t=new Date(e.thread.updatedAt*1e3).toISOString();return OO({model:EO(e.model),reasoningEffort:DO(e.reasoningEffort),approvalPolicy:null,sandboxMode:null,updatedAt:t})}function wO(e){return{id:e.id,status:e.status,error:e.error?fD(uD(e.error)):null,items:e.items.map(e=>cD(e))}}function TO(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 EO(e){return pD(e)?.trim()||void 0}function DO(e){return e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`||e===`max`?e:null}function OO(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 kO=5e3,AO=`Request interrupted by user`,jO=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=ZD(this.activeSessionConfig,t?.sessionConfig),t?.mode===`plan`&&(this.activeSessionConfig.permissionMode=`plan`);let n=new AbortController,r=this.createQuery({prompt:e,model:this.activeModel,sessionConfig:this.activeSessionConfig,resume:this.resumeSessionId,abortController:n,canUseTool:this.handleCanUseTool});this.activeAbortController=n,this.activeQuery=r,this.emitSyntheticUserInputEvents(e),this.startQueryLoop(r)}async interrupt(){if(!this.turnInProgress||this.closed)return;this.interruptRequested=!0;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=IO(t),i={...n.input,answers:r};n.resolve({behavior:`allow`,updatedInput:i}),this.emit({type:`user.input.resolved`,requestId:e,status:`submitted`,answeredCount:QD(r),questions:PO(n.input),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=nk(t);this.captureResumeSessionId(t),this.emit({type:`native.raw`,source:`claude.query`,native_type:rk(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??AO);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)=>NO(e,t)?this.requestUserInput(e,t,n):MO(n)?this.requestToolPermission(e,t,n):{behavior:`allow`};requestToolPermission(e,t,n){let r=`req_${Cw(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=PO(t),i=`req_${Cw(8)}`;return this.emit({type:`user.input.requested`,requestId:i,tool_name:e,turn_id:this.activeTurnId,questions:r,source_event_type:`can_use_tool`}),new Promise((e,r)=>{if(n.signal.aborted){e({behavior:`deny`,message:`Operation aborted`,interrupt:!0});return}let a=()=>{n.signal.removeEventListener(`abort`,a),this.pendingUserInputRequests.has(i)&&(this.pendingUserInputRequests.delete(i),e({behavior:`deny`,message:`Operation aborted`,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:i,status:`expired`,answeredCount:0,source_event_type:`abort`}))};n.signal.addEventListener(`abort`,a,{once:!0}),this.pendingUserInputRequests.set(i,{input:t,resolve:t=>{n.signal.removeEventListener(`abort`,a),e(t)},reject:e=>{n.signal.removeEventListener(`abort`,a),r(e)}})})}expirePendingToolPermissionRequests(e){for(let[t,n]of this.pendingToolPermissionRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`tool.permission.resolved`,requestId:t,decision:`deny`,reason:e,toolName:n.toolName,itemId:n.toolUseID,source_event_type:`session_end`});this.pendingToolPermissionRequests.clear()}expirePendingUserInputRequests(e){for(let[t,n]of this.pendingUserInputRequests.entries())n.resolve({behavior:`deny`,message:e,interrupt:!0}),this.emit({type:`user.input.resolved`,requestId:t,status:`expired`,answeredCount:0,source_event_type:`session_end`});this.pendingUserInputRequests.clear()}emit(e){for(let t of this.listeners)t(e)}ensureOpen(){if(this.closed)throw Error(`Session ${this.id} is closed`)}clearTurnState(){this.activeTurnId=null,this.activeAssistantItemId=null,this.assistantStarted=!1,this.assistantCompleted=!1,this.activeToolItemId=null,this.toolStarted=!1,this.activeTurnStarted=!1,this.activeTurnTerminalEmitted=!1}armInterruptFallback(e,t){this.clearInterruptFallbackTimer(),this.interruptFallbackTimer=setTimeout(()=>{this.closed||!this.turnInProgress||!this.interruptRequested||this.activeQuery!==e||(e.close?.(),t?.abort())},kO)}clearInterruptFallbackTimer(){this.interruptFallbackTimer&&=(clearTimeout(this.interruptFallbackTimer),null)}captureResumeSessionId(e){let t=nk(e),n=rk(t.session_id)??rk(t.sessionId);n&&(this.resumeSessionId=n)}emitSyntheticUserInputEvents(e){if(!e.trim())return;let t=new Date().toISOString(),n=this.resumeSessionId??this.id,r=`claude_user_${Cw(10)}`,i={parentUuid:null,isSidechain:!1,userType:`external`,cwd:this.cwd,sessionId:n,session_id:n,version:`synthetic`,type:`user`,message:{role:`user`,content:[{type:`text`,text:e}]},uuid:r,timestamp:t,permissionMode:this.activeSessionConfig.permissionMode??`default`,source_event_type:`claude.synthetic.user_input`};this.emit({type:`native.raw`,source:`claude.synthetic.user_input`,native_type:`user`,message:i});let a=this.mapClaudeMessage(i);for(let e of a)this.emit(e)}ensureAssistantItemId(e){let t=sk(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=rk(e.tool_id)??rk(e.tool_use_id)??ak(e.preceding_tool_use_ids);if(t)return this.activeToolItemId=t,t;let n=rk(e.uuid);if(n)return this.activeToolItemId=n,n;let r=ck(rk(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=nk(e),n=rk(t.type);if(n===`user`){let e=this.mapStructuredClaudeToolResult(t);if(e.length>0)return e;if(!XO(t))return[];let n=ZO(nk(t.message));return n?[{type:`item.completed`,item:{id:rk(t.uuid)??`claude_user_${Date.now()}`,type:`user_message`,text:n,turn_id:this.activeTurnId,source_event_type:rk(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=YO(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=nk(t.event);if(rk(e.type)===`message_start`){let t=sk(e);return t&&(this.activeAssistantItemId=t,this.assistantStarted=!1,this.assistantCompleted=!1),[]}let n=QO(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||rk(t.subtype)?.startsWith(`error_`)===!0){let n=ek(t,this.interruptRequested),r=$O(t,n);return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.failed`,...n?{status:`interrupted`}:{},error:{message:r},usage:tk(t.usage),turn_id:this.activeTurnId,source_event_type:`result`}]}return this.activeTurnTerminalEmitted=!0,[...e,...this.buildAssistantCompletionTailEvent(),{type:`turn.completed`,usage:tk(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=rk(t.summary)??`tool summary`,i=rk(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=rk(t.tool_name)??`tool`,i=rk(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=rk(t.subtype);if(e===`init`){let e=this.maybeCreateThreadStartedEvent(rk(t.session_id)??rk(t.sessionId),`claude.system.init`);return e?[e]:[]}return e===`status`?[{type:`status.progress`,message:rk(t.status)??`status update`}]:[{type:`status.progress`,message:e?`system.${e}`:`system event`}]}if(n===`auth_status`){let e=rk(t.error);return e?[{type:`error`,message:e}]:[{type:`status.progress`,message:`auth status update`}]}return[]}mapStructuredClaudeToolUse(e){let t=LO(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=RO(e);if(!t)return[];let n=this.pendingClaudeToolUses.get(t.toolUseId);if(!n)return[];this.pendingClaudeToolUses.delete(t.toolUseId);let r=zO({toolUse:n,toolUseId:t.toolUseId,raw:e,turnId:this.activeTurnId});return r?[...this.maybeEmitTurnStarted(`user.tool_use_result`),{type:`item.completed`,item:r}]:[]}maybeCreateThreadStartedEvent(e,t){return this.threadStartedEmitted?null:(this.threadStartedEmitted=!0,{type:`thread.started`,thread_id:e??this.resumeSessionId??this.id,source:t})}maybeEmitTurnStarted(e){return this.activeTurnStarted||!this.activeTurnId?[]:(this.activeTurnStarted=!0,[{type:`turn.started`,turn_id:this.activeTurnId,source_event_type:e}])}};function MO(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 NO(e,t){let n=e.toLowerCase();return n.includes(`askuserquestion`)||n.includes(`request_user_input`)?!0:Array.isArray(t.questions)}function PO(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=FO(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 FO(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 IO(e){let t={};for(let[n,r]of Object.entries(e??{}))t[n]=Array.isArray(r)?r.map(e=>String(e)):[];return t}function LO(e){let t=nk(e.message),n=Array.isArray(t.content)?t.content:[],r=[];for(let e of n){let t=nk(e);if(t.type!==`tool_use`)continue;let n=rk(t.id),i=rk(t.name),a=nk(t.input);if(!(!n||!i)){if(i===`Task`){let e=rk(a.subagent_type),t=rk(a.description)??e??`任务`;r.push({id:n,toolName:`Task`,title:`${e??`Task`}(${t})`,pendingStatusLabel:`运行中`,prompt:rk(a.prompt),responseLabel:`Response`,subagentType:e,description:t});continue}if(i===`Read`){let e=rk(a.file_path);r.push({id:n,toolName:`Read`,title:`Read 1 file`,pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e});continue}if(i===`Write`){let e=rk(a.file_path);r.push({id:n,toolName:`Write`,title:WO(e),pendingStatusLabel:`运行中`,responseLabel:`Preview`,filePath:e})}}}return r}function RO(e){let t=nk(e.message),n=Array.isArray(t.content)?t.content:[];for(let e of n){let t=nk(e);if(t.type!==`tool_result`)continue;let n=rk(t.tool_use_id);if(n)return{toolUseId:n}}return null}function zO(e){let t=nk(e.raw.tool_use_result),n=BO(t.content)??ZO(nk(e.raw.message)),r=nk(t.usage),i=ok(t.totalTokens)??ok(r.total_tokens)??ok(r.output_tokens),a=ok(t.totalToolUseCount),o=ok(t.totalDurationMs),s=rk(t.agentId),c=rk(t.filePath)??e.toolUse.filePath;if(e.toolUse.toolName===`Task`){let t=HO(a,i,o);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:t,status:`completed`,status_label:t,display_as:`tool_card`,prompt:e.toolUse.prompt,response:n,response_label:e.toolUse.responseLabel,subagent_type:e.toolUse.subagentType,description:e.toolUse.description,agent_id:s,total_tokens:i,total_tool_uses:a,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Read`){let r=VO(t)??n;return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:`Done`,status:`completed`,status_label:`Done`,display_as:`tool_card`,response:r,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}if(e.toolUse.toolName===`Write`){let n=ik(t.content),r=UO(KO(n),c);return{id:e.toolUseId,type:`tool_status`,turn_id:e.turnId,tool_name:e.toolUse.toolName,title:e.toolUse.title,text:r,status:`completed`,status_label:r,display_as:`tool_card`,response:n,response_label:e.toolUse.responseLabel,file_path:c,total_tokens:i,duration_ms:o,source_event_type:`user.tool_use_result`}}return null}function BO(e){if(typeof e==`string`&&e.length>0)return e;if(!Array.isArray(e))return;let t=[];for(let n of e){let e=nk(n);e.type===`text`&&typeof e.text==`string`&&e.text.length>0&&t.push(e.text)}return t.length>0?t.join(`
|
|
516
516
|
`):void 0}function VO(e){return ik(nk(e.file).content)||BO(e.content)}function HO(e,t,n){let r=[`Done`];return typeof e==`number`&&r.push(`${e} tool uses`),typeof t==`number`&&r.push(`${qO(t)} tokens`),typeof n==`number`&&r.push(JO(n)),r.join(` · `)}function UO(e,t){let n=typeof e==`number`?`Wrote ${e} lines`:`Wrote file`;return t?`${n} to ${t}`:n}function WO(e){return typeof e==`string`&&e.includes(`/.claude/plans/`)?`Updated plan`:typeof e==`string`?`Write(${GO(e)})`:`Write`}function GO(e){let t=e.split(`/`);return t[t.length-1]||e}function KO(e){if(e)return e.split(`
|
|
517
517
|
`).length}function qO(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function JO(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 YO(e){return ZO(nk(e.message))||(ik(e.result)??``)}function XO(e){if(typeof e.parent_tool_use_id==`string`&&e.parent_tool_use_id.length>0||e.isSidechain===!0)return!1;let t=nk(e.message);return!(Array.isArray(t.content)?t.content:[]).some(e=>nk(e).type===`tool_result`)}function ZO(e){let t=ik(e.content);if(t)return t;let n=ik(e.text)??ik(e.prompt);if(n)return n;let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){let t=nk(e);t.type===`text`&&typeof t.text==`string`&&t.text.length>0&&i.push(t.text)}if(i.length>0)return i.join(`
|
|
518
518
|
`)}function QO(e){let t=nk(nk(e.event).delta);if(typeof t.text==`string`&&t.text.length>0)return t.text}function $O(e,t=!1){if(t)return AO;let n=Array.isArray(e.errors)?e.errors.filter(e=>typeof e==`string`):[];return n.length>0?n.join(`; `):rk(e.subtype)||`Claude turn failed`}function ek(e,t){return t||(rk(e.terminal_reason)??rk(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 tk(e){let t=nk(e);return{input_tokens:ok(t.input_tokens)??ok(t.inputTokens)??0,cached_input_tokens:ok(t.cached_input_tokens)??ok(t.cache_read_input_tokens)??ok(t.cacheReadInputTokens)??0,output_tokens:ok(t.output_tokens)??ok(t.outputTokens)??0}}function nk(e){return typeof e==`object`&&e?e:{}}function rk(e){if(typeof e==`string`&&e.trim())return e}function ik(e){if(typeof e==`string`&&e.length>0)return e}function ak(e){if(Array.isArray(e)){for(let t of e)if(typeof t==`string`&&t.trim())return t}}function ok(e){if(typeof e==`number`&&Number.isFinite(e))return e}function sk(e){let t=rk(nk(e.message).id);if(t)return t;let n=rk(nk(nk(e.event).message).id);if(n)return n}function ck(e){let t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`_`);return t?t.replace(/^_+|_+$/g,``):`tool`}var lk=class{constructor(e,t,n,r){this.nativeSession=r,this.provider=e,this.id=t,this.model=n,this.bindNativeEvents(r)}id;provider;providerMode=`native`;model;listeners=new Set;unsubscribe;onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async sendInput(e,t){if(typeof this.nativeSession?.sendInput==`function`){await this.nativeSession.sendInput(e);return}if(typeof this.nativeSession?.input==`function`){await this.nativeSession.input(e);return}if(typeof this.nativeSession?.turn==`function`){await this.nativeSession.turn({input:e});return}throw Error(`Native session does not expose a known input method`)}async interrupt(){if(typeof this.nativeSession?.interrupt==`function`){await this.nativeSession.interrupt();return}if(typeof this.nativeSession?.cancel==`function`){await this.nativeSession.cancel();return}throw Error(`Native session does not expose interrupt/cancel`)}async close(){if(typeof this.unsubscribe==`function`&&(this.unsubscribe(),this.unsubscribe=void 0),typeof this.nativeSession?.close==`function`){await this.nativeSession.close();return}if(typeof this.nativeSession?.dispose==`function`){await this.nativeSession.dispose();return}}async respondToolPermission(e,t,n){if(typeof this.nativeSession?.respondToolPermission==`function`){await this.nativeSession.respondToolPermission({requestId:e,decision:t,reason:n});return}if(typeof this.nativeSession?.approveToolCall==`function`){await this.nativeSession.approveToolCall({requestId:e,approved:t===`allow`,reason:n});return}throw Error(`Native session does not expose tool approval response method`)}bindNativeEvents(e){let t=e=>{let t=uk(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 uk(e){return typeof e==`object`&&e&&`type`in e?e:{type:`status.progress`,nativeEvent:e}}var dk=`@anthropic-ai/claude-agent-sdk`,fk=`claude-sonnet-4-6`,pk=1e4,mk=class{constructor(e,t){this.preferNative=e,this.requireNative=t}provider=`claude`;async isNativeAvailable(){try{return await import(dk),!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(dk),n=await hk(gk(t,e),pk,`Claude native query session creation timed out`);if(n)return n;let r=await hk(_k(t,e),pk,`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 hk(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 gk(e,t){let n=vk(e);if(!n)return null;let r=t.model??fk;return new jO(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=yk(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 _k(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 lk(`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 lk(`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 lk(`claude`,t.sessionId,t.model,n)}return null}function vk(e){if(typeof e?.query==`function`)return e.query;if(typeof e?.default?.query==`function`)return e.default.query}function yk(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 bk(e,t={}){let n=t.preferNative??!1,r=t.requireNative??!1;return e===`codex`?new pO(n,r):new mk(n,r)}const xk=p.default.join(`.claude`,`projects`),Sk=/\u001B\[[0-?]*[ -/]*[@-~]/g;async function Ck(e){return(await(0,O.listSessions)(typeof e==`number`?{limit:e}:void 0)).map(e=>Ak(e)).filter(e=>typeof e.cwd==`string`).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}async function wk(e,t){let n=Ok(e,t?.homeDir),r=p.default.resolve(e);try{let i=await jk(e,n,r,{maxSessions:cA(t?.maxSessions),updatedAfterMs:sA(t?.updatedAfterMs)});if(i.length>0)return i}catch{}return Mk(n,{maxSessions:cA(t?.maxSessions),updatedAfterMs:sA(t?.updatedAfterMs)})}async function Tk(e){let t=await qk(e.nativeSessionId,e.projectPath),n=await Jk(e.projectPath,e.nativeSessionId,e.homeDir),r=Fk(t,{createdAtFallbackMs:n.birthtimeMs,updatedAtFallbackMs:n.mtimeMs}),i=Rk(r.updatedAt,n.mtimeMs),a=Ik(r.model);return{rawEvents:Ek({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:zk(t),nativeWatchPath:Dk(e.projectPath,e.nativeSessionId,e.homeDir)}}function Ek(e){let t=[],n=Fk(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 Dk(e,t,n){return p.default.join(Ok(e,n),`${t}.jsonl`)}function Ok(e,t){let n=t??f.default.homedir();return p.default.join(n,xk,kk(e))}function kk(e){let t=p.default.resolve(e).replace(/\\/g,`/`).replace(/:/g,`-`).replace(/\//g,`-`);return t.startsWith(`-`)?t:`-${t}`}function Ak(e){let t=rA(e.customTitle)??rA(e.summary)??rA(e.firstPrompt),n=Gk(e.createdAt??e.lastModified),r=Gk(e.lastModified);return{nativeSessionId:e.sessionId,cwd:Wk(e.cwd),title:t,createdAt:n,updatedAt:r,status:`idle`}}async function jk(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=sA(e.lastModified);if(r.updatedAfterMs!==void 0&&i!==void 0&&i<r.updatedAfterMs){s=!0;break}let o=Ak(e);if(typeof o.cwd!=`string`||p.default.resolve(o.cwd)!==n)continue;let c=await Nk(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 Pk(a,r)}async function Mk(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 Nk(e,{nativeSessionId:t.name.slice(0,-6)});n&&r.push(n)}return Pk(r,t)}async function Nk(e,t){let n=p.default.join(e,`${t.nativeSessionId}.jsonl`),r;try{r=await Kk(n)}catch(e){if(e.code===`ENOENT`)return t.sdkSession;throw e}if(!Uk(r))return;let i=await d.default.stat(n),a=t.sdkSession?.createdAt?oA(t.sdkSession.createdAt):void 0,o=t.sdkSession?.updatedAt?oA(t.sdkSession.updatedAt):void 0,s=Fk(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:zk(r)}}function Pk(e,t){let n=e.filter(e=>{if(t.updatedAfterMs===void 0)return!0;let n=oA(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 Fk(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=eA(Qk(tA(t.raw.message))));let e=Lk(t);e&&(n=e)}let o=i??sA(t.createdAtFallbackMs)??0,s=a??sA(t.updatedAtFallbackMs)??o;return{model:n,title:r,createdAt:new Date(o).toISOString(),updatedAt:new Date(s).toISOString()}}function Ik(e){let t=Wk(e);if(t)return{mode:`default`,model:t,reasoningEffort:null}}function Lk(e){return Wk(tA(e.raw.message).model)??Wk(e.raw.model)}function Rk(e,t){let n=oA(e)??0,r=sA(t)??0;return new Date(Math.max(n,r)).toISOString()}function zk(e,t=Date.now()){let n=null;for(let t of e){let e=Bk(t);e&&(n=e)}return!n?.unresolved||n.timestampMs!==void 0&&t-n.timestampMs>6e5?`idle`:`running`}function Bk(e){let t=e.timestampMs??oA(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 Vk(e.raw,t);default:return null}}function Vk(e,t){let n=tA(e);if(n.isMeta===!0)return null;let r=tA(n.message);if(Zk(r).length>0)return{unresolved:!0,timestampMs:t};let i=Qk(r);return i?Hk(i)?{unresolved:!1,timestampMs:t}:{unresolved:!0,timestampMs:t}:null}function Hk(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 Uk(e){for(let t of e){if(t.type===`user`){let e=tA(t.raw.message);if(Qk(e)||Zk(e).length>0)return!0;continue}if(t.type!==`assistant`)continue;let e=tA(t.raw.message);if(Qk(e)||Xk(e).length>0||nA(t.raw.error))return!0}return!1}function Wk(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function Gk(e){return Number.isFinite(e)?new Date(e).toISOString():new Date(0).toISOString()}async function Kk(e){let t=(await d.default.readFile(e,`utf8`)).split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "craby-gateway",
|
|
3
|
-
"version": "0.27.
|
|
3
|
+
"version": "0.27.5",
|
|
4
4
|
"description": "Craby desktop gateway CLI",
|
|
5
5
|
"bin": {
|
|
6
6
|
"craby-gateway": "dist-sea/gateway.cjs"
|
|
@@ -22,6 +22,6 @@
|
|
|
22
22
|
"directory": "apps/desktop-gateway"
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@anthropic-ai/claude-agent-sdk": "^0.2.
|
|
25
|
+
"@anthropic-ai/claude-agent-sdk": "^0.2.118"
|
|
26
26
|
}
|
|
27
27
|
}
|