craby-gateway 0.30.6 → 0.30.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`module`),h=require(`node:child_process`),g=require(`node:module`),_=require(`node:url`),v=require(`node:readline`);v=c(v);let y=require(`node:process`);y=c(y);let b=require(`node:util`),x=require(`node:http`),S=require(`node:https`),C=require(`node:stream/promises`),w=require(`path`);w=c(w);let T=require(`node:string_decoder`),E=require(`net`),D=require(`child_process`),O=require(`@anthropic-ai/claude-agent-sdk`);var k={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.30.6`,description:`Craby desktop gateway CLI`,type:`module`,bin:{"craby-gateway":`dist-sea/gateway.cjs`},files:[`dist-sea`,`README.md`],publishConfig:{access:`public`,registry:`https://registry.npmjs.org/`},engines:{node:`>=20`},repository:{type:`git`,url:`git+https://github.com/wuyongzhi/anycoding.git`,directory:`apps/desktop-gateway`},scripts:{dev:`GATEWAY_PORT=18787 GATEWAY_HTTPS_PORT=18787 GATEWAY_AUDIT_LOG_PATH=./logs/audit.log GATEWAY_LOG_PATH=./logs/gateway.log GATEWAY_SESSION_HISTORY_DIR=./logs/sessions-v2 GATEWAY_PROJECT_STORE_DIR=./logs/projects GATEWAY_AUTH_STORE_DIR=./logs/auth tsx watch src/index.ts --config ./logs/gateway.dev.yaml`,build:`tsup src/index.ts --format esm --dts`,"build:workspace-deps":`pnpm --filter @remote-agent/contracts run build && pnpm --filter @remote-agent/provider-adapters run build`,"build:bundle":`pnpm run build:workspace-deps && tsdown --config tsdown.config.ts`,"build:npm":`pnpm run build:bundle && node ./scripts/preparePublishPackage.mjs`,"start:bundle":`node dist-sea/gateway.cjs`,"build:blob:darwin":`pnpm run build:bundle && node --experimental-sea-config sea-config.darwin.json`,"build:blob:linux":`pnpm run build:bundle && node --experimental-sea-config sea-config.linux.json`,"build:blob:win32":`pnpm run build:bundle && node --experimental-sea-config sea-config.win32.json`,"build:bin":`pnpm run build:bin:current`,"build:bin:current":`pnpm run build:bundle && node ./scripts/buildSea.mjs`,"build:bin:darwin":`pnpm run build:bundle && node ./scripts/buildSea.mjs darwin`,"build:bin:linux":`pnpm run build:bundle && node ./scripts/buildSea.mjs linux`,"build:bin:win32":`pnpm run build:bundle && node ./scripts/buildSea.mjs win32`,test:`vitest run --passWithNoTests`,typecheck:`tsc -p tsconfig.json --noEmit`,"dump:codex-history":`tsx src/dumpCodexSessionHistory.ts`,"export:codex-project-history":`tsx src/exportCodexProjectHistory.ts`,"mobile:ios-ota:publish":`tsx src/mobileIosOtaInstall.ts`,"pairing:start":`tsx src/pairingStart.ts`,"pack:check":`pnpm run build:npm && npm pack --dry-run ./dist-npm --userconfig ../../.npmrc`,"publish:npm":`pnpm run build:npm && npm publish ./dist-npm --access public --userconfig ../../.npmrc`},dependencies:{"@anthropic-ai/claude-agent-sdk":`^0.2.118`,"@fastify/compress":`^8.3.1`,"@fastify/cors":`^10.0.2`,"@fastify/websocket":`^11.0.2`,diff:`^7.0.0`,fastify:`^5.2.1`,jsonwebtoken:`^9.0.2`,nanoid:`^5.1.5`,pino:`^10.3.1`,"qrcode-terminal":`^0.12.0`,ws:`^8.18.3`,yaml:`^2.8.2`},devDependencies:{"@remote-agent/contracts":`workspace:*`,"@remote-agent/provider-adapters":`workspace:*`,"@types/diff":`^7.0.1`,"@types/jsonwebtoken":`^9.0.9`,"@types/qrcode-terminal":`^0.12.2`,"@types/ws":`^8.5.13`,postject:`^1.0.0-alpha.6`,tsdown:`^0.21.0`}};const A=/(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/;function j(e){let t=e.match(A);return t?t[0]:null}function M(e){return typeof e==`string`?j(e):null}function N(e,t){let n=F(e),r=F(t);if(!n||!r)throw Error(`Invalid version comparison: ${e} vs ${t}`);return n.major===r.major?n.minor===r.minor?n.patch===r.patch?n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease.localeCompare(r.prerelease):-1:1:n.patch-r.patch:n.minor-r.minor:n.major-r.major}function P(e,t){return N(e,t)>=0}function F(e){let t=e.match(A);return t?{major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3]),prerelease:typeof t[4]==`string`?t[4]:null}:null}const I=k,L=I.dependencies??{};function R(e){return L[e]??``}const z={packageName:`craby-gateway`,cliName:`craby-gateway`,version:I.version??`0.0.0`,providerRequirements:[{id:`codex`,dependencyName:null,dependencyRange:``,minimumVersion:null,systemCommand:`codex`,versionArgs:[`--version`],systemCommandRequired:!0,displayName:`Codex`},{id:`claude`,dependencyName:`@anthropic-ai/claude-agent-sdk`,dependencyRange:R(`@anthropic-ai/claude-agent-sdk`),minimumVersion:M(R(`@anthropic-ai/claude-agent-sdk`)),systemCommand:`claude`,versionArgs:[`--version`],systemCommandRequired:!1,displayName:`Claude Code`}]};function ee(e){let t=`start`,n,r=!1,i=!1,a=[...e],o=a[0]?.trim();if(o&&!o.startsWith(`-`))if(o===`start`||o===`init`||o===`doctor`||o===`help`||o===`__worker`)t=o,a.shift();else throw Error(`Unknown command: ${o}`);for(let e=0;e<a.length;e+=1){let o=a[e];if(o===`--config`){n=B(o,a[e+1]),e+=1;continue}if(o===`--force`){r=!0;continue}if(o===`--log`){i=!0;continue}if(o===`--help`||o===`-h`){t=`help`;continue}if(o===`--version`||o===`-v`){t=`version`;continue}throw Error(`Unknown argument: ${o}`)}return{command:t,configPath:n,force:r,logToConsole:i}}function B(e,t){let n=t?.trim();if(!n)throw Error(`${e} requires a value`);return n}var V=o((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),te=o((e=>{var t=V();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),H=o((e=>{var t=V(),n=te();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags);break}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||(!e||a.some(e=>e.startsWith(n)))&&r.push(`%TAG ${t} ${n}`);return r.join(`
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let l=require(`node:crypto`),u=require(`node:fs`);u=c(u);let d=require(`node:fs/promises`);d=c(d);let f=require(`node:os`);f=c(f);let p=require(`node:path`);p=c(p);let m=require(`module`),h=require(`node:child_process`),g=require(`node:module`),_=require(`node:url`),v=require(`node:readline`);v=c(v);let y=require(`node:process`);y=c(y);let b=require(`node:util`),x=require(`node:http`),S=require(`node:https`),C=require(`node:stream/promises`),w=require(`path`);w=c(w);let T=require(`node:string_decoder`),E=require(`net`),D=require(`child_process`),O=require(`@anthropic-ai/claude-agent-sdk`);var k={name:`@remote-agent/desktop-gateway`,private:!0,version:`0.30.7`,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
  `)?`
@@ -130,7 +130,7 @@ ${n.output}`:n.output:t.push({item:{...bs(`claude-command-output:${e.eventId}`,e
130
130
  `).trim();if(!t)return;let n=t.split(`
131
131
  `).find(e=>e.trim().length>0);if(n)return n.slice(0,160)}function tc(e){let t=ac(e);if(!t||!nc(t))return null;if(ic(t,`local-command-caveat`))return{kind:`ignored_meta`};let n=ic(t,`command-name`),r=ic(t,`command-message`),i=ic(t,`command-args`),a=ic(t,`local-command-stdout`);if(n||r){let e=n?n.startsWith(`/`)?n:`/${n}`:r?.startsWith(`/`)?r:`/${r??``}`;return{kind:`command_strip`,command:i?`${e} ${i}`.trim():e,label:r??void 0,args:i??void 0,output:a??void 0}}let o=ic(t,`bash-input`);if(o)return{kind:`command_strip`,command:o.startsWith(`!`)?o:`!${o}`,output:rc(ic(t,`bash-stdout`),ic(t,`bash-stderr`))};let s=rc(a??ic(t,`bash-stdout`),ic(t,`bash-stderr`));return s?{kind:`command_output`,output:s}:null}function nc(e){if(!e.startsWith(`<`)||!e.endsWith(`>`))return!1;let t=e;for(;t.length>0;){let e=t.match(ko);if(!e)return!1;t=t.slice(e[0].length)}return!0}function rc(e,t){let n=[e,t].filter(e=>typeof e==`string`&&e.length>0);if(n.length!==0)return n.join(`
132
132
  `)}function ic(e,t){return ac(e.match(RegExp(`<${t}>([\\s\\S]*?)</${t}>`,`i`))?.[1])??null}function ac(e){if(typeof e!=`string`)return;let t=e.replace(Ao,``).replace(/\r\n/g,`
133
- `).trim();return t.length>0?t:void 0}function oc(e){return Do.test(e)}function sc(e){return e===`failed`?`error`:e===`streaming`?`accent`:e===`waiting_approval`||e===`waiting_input`?`warning`:`success`}function cc(e){let t=_c(e.payload.raw);return yc(t,[`turn_id`,`turnId`])||yc(_c(t.item),[`turn_id`,`turnId`])||yc(_c(t.turn),[`id`,`turn_id`,`turnId`])||yc(_c(_c(t.message).params),[`turnId`,`turn_id`])}function lc(e){return e.type===`native.raw`?yc(_c(_c(e.payload.raw).message),[`method`]):e.type}function uc(e){let t=_c(e.payload.raw),n=_c(t.item);return Object.keys(n).length>0?n:_c(_c(_c(t.message).params).item)}function dc(e){if(!e)return;let t=e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase();return t.length>0?t:void 0}function fc(e){let t=lc(e);return t!==`item.started`&&t!==`item.completed`&&t!==`item/started`&&t!==`item/completed`?!1:dc(yc(uc(e),[`type`]))===`user_message`}function pc(e){let t=lc(e);return t!==`item.started`&&t!==`item.completed`&&t!==`item/started`&&t!==`item/completed`?!1:dc(yc(uc(e),[`type`]))===`reasoning`}function mc(e){if(e.type===`turn.completed`||e.type===`turn.failed`)return!0;let t=yc(_c(_c(e.payload.raw).message),[`method`]);return t===`turn/completed`||t===`turn/failed`||t===`turn/interrupted`}function hc(e){let t=_c(_c(e.payload.raw).item),n=yc(t,[`type`]);if(n&&(n===`command_execution`||n===`file_change`||n===`web_search`))return t}function gc(e){let t=yc(e,[`type`]);if(t===`file_change`)return`正在编辑`;if(t===`web_search`)return`正在搜索`;if(t===`command_execution`){let t=Array.isArray(e?.command_actions)?e.command_actions:Array.isArray(e?.commandActions)?e.commandActions:[],n=!1,r=!1;for(let e of t){let t=yc(_c(e),[`type`]);t===`read`||t===`listFiles`||t===`list_files`?n=!0:t===`search`&&(r=!0)}return r?`正在搜索`:n?`正在浏览`:`正在运行命令`}return`正在思考`}function _c(e){return typeof e==`object`&&e?e:{}}function vc(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function yc(e,t){let n=e??{};for(let e of t){let t=n[e];if(typeof t==`string`&&t.trim())return t}}function bc(e,t){let n=e??{};for(let e of t){let t=n[e];if(typeof t==`number`&&Number.isFinite(t))return t}}function xc(e){let t=new Set,n=[];for(let r of e)!r||t.has(r)||(t.add(r),n.push(r));return n}function Sc(e){let t=e.replace(/\\/g,`/`).split(`/`);return t[t.length-1]??e}function Cc(e){return e?e.replace(/\r\n/g,`
133
+ `).trim();return t.length>0?t:void 0}function oc(e){return Do.test(e)}function sc(e){return e===`failed`?`error`:e===`streaming`?`accent`:e===`waiting_approval`||e===`waiting_input`?`warning`:`success`}function cc(e){let t=_c(e.payload.raw),n=yc(t,[`turn_id`,`turnId`]);if(n)return n;let r=yc(_c(t.item),[`turn_id`,`turnId`]);if(r)return r;let i=yc(_c(t.turn),[`id`,`turn_id`,`turnId`]);if(i)return i;let a=_c(t.message),o=yc(a,[`turn_id`,`turnId`]);if(o)return o;let s=yc(_c(a.item),[`turn_id`,`turnId`]);if(s)return s;let c=yc(_c(a.turn),[`id`,`turn_id`,`turnId`]);if(c)return c;let l=_c(a.params);return yc(l,[`turnId`,`turn_id`])??yc(_c(l.turn),[`id`,`turn_id`,`turnId`])??yc(_c(l.item),[`turn_id`,`turnId`])}function lc(e){if(e.type!==`native.raw`)return e.type;let t=_c(e.payload.raw),n=_c(t.message),r=yc(n,[`method`])??yc(t,[`method`]);if(r)return r;if(yc(n,[`scope`])===`item`)return`item.completed`}function uc(e){let t=_c(e.payload.raw),n=_c(t.item);if(Object.keys(n).length>0)return n;let r=_c(t.message),i=_c(r.item);return Object.keys(i).length>0?i:_c(_c(r.params).item)}function dc(e){if(!e)return;let t=e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase();return t.length>0?t:void 0}function fc(e){let t=lc(e);return t!==`item.started`&&t!==`item.completed`&&t!==`item/started`&&t!==`item/completed`?!1:dc(yc(uc(e),[`type`]))===`user_message`}function pc(e){let t=lc(e);return t!==`item.started`&&t!==`item.completed`&&t!==`item/started`&&t!==`item/completed`?!1:dc(yc(uc(e),[`type`]))===`reasoning`}function mc(e){if(e.type===`turn.completed`||e.type===`turn.failed`)return!0;let t=_c(e.payload.raw),n=_c(t.message),r=yc(n,[`method`])??yc(t,[`method`]);if(r===`turn/completed`||r===`turn/failed`||r===`turn/interrupted`)return!0;if(yc(n,[`scope`])!==`turn`)return!1;let i=yc(_c(n.turn),[`status`]);return i===`completed`||i===`failed`||i===`interrupted`}function hc(e){let t=_c(_c(e.payload.raw).item),n=yc(t,[`type`]);if(n&&(n===`command_execution`||n===`file_change`||n===`web_search`))return t}function gc(e){let t=yc(e,[`type`]);if(t===`file_change`)return`正在编辑`;if(t===`web_search`)return`正在搜索`;if(t===`command_execution`){let t=Array.isArray(e?.command_actions)?e.command_actions:Array.isArray(e?.commandActions)?e.commandActions:[],n=!1,r=!1;for(let e of t){let t=yc(_c(e),[`type`]);t===`read`||t===`listFiles`||t===`list_files`?n=!0:t===`search`&&(r=!0)}return r?`正在搜索`:n?`正在浏览`:`正在运行命令`}return`正在思考`}function _c(e){return typeof e==`object`&&e?e:{}}function vc(e){if(typeof e!=`string`)return;let t=e.trim();return t.length>0?t:void 0}function yc(e,t){let n=e??{};for(let e of t){let t=n[e];if(typeof t==`string`&&t.trim())return t}}function bc(e,t){let n=e??{};for(let e of t){let t=n[e];if(typeof t==`number`&&Number.isFinite(t))return t}}function xc(e){let t=new Set,n=[];for(let r of e)!r||t.has(r)||(t.add(r),n.push(r));return n}function Sc(e){let t=e.replace(/\\/g,`/`).split(`/`);return t[t.length-1]??e}function Cc(e){return e?e.replace(/\r\n/g,`
134
134
  `).split(`
135
135
  `):[]}var wc=Y([`text`,`output`]),Tc=q({id:G().min(1),field:wc,delta:G()});function Ec(e,t){let n=new Map(e.map(e=>[e.id,e])),r=new Map(t.map(e=>[e.id,e])),i=e.filter(e=>!r.has(e.id)).map(e=>e.id),a=[],o=[];for(let e of t){let t=n.get(e.id);if(!t){a.push(e);continue}if(jc(t)===jc(e))continue;let r=Dc(t,e);if(!r){a.push(e);continue}o.push(...r)}return{upserts:a,removals:i,textDeltaPatches:o}}function Dc(e,t){if(e.kind!==t.kind)return null;let n=Oc(e);if(n.length===0||Mc(Ac(e))!==Mc(Ac(t)))return null;let r=[];for(let i of n){let n=kc(e,i),a=kc(t,i);if(n!==a){if(typeof n!=`string`||typeof a!=`string`||!a.startsWith(n)||a.length<=n.length)return null;r.push({id:t.id,field:i,delta:a.slice(n.length)})}}return r.length>0?r:null}function Oc(e){switch(e.kind){case`agent_commentary`:case`activity_summary`:return[`text`];case`terminal_card`:case`command_strip`:return[`output`];default:return[]}}function kc(e,t){return t===`text`?`text`in e&&typeof e.text==`string`?e.text:void 0:`output`in e&&typeof e.output==`string`?e.output:void 0}function Ac(e){if(e.kind===`agent_commentary`||e.kind===`activity_summary`){let{text:t,...n}=e;return n}if(e.kind===`terminal_card`||e.kind===`command_strip`){let{output:t,...n}=e;return n}return e}function jc(e){return JSON.stringify(e)}function Mc(e){return JSON.stringify(e)}var Nc=G().trim().min(1).nullable(),Pc=Y([`default`,`plan`]),Fc=q({approvalPolicy:Ia.nullable(),sandboxMode:La.nullable()}),Ic=q({permissionMode:Ra.nullable()}),Lc=q({codex:Fc.optional(),claude:Ic.optional()}),Rc=nr(Qn());q({modeDefault:Pc,model:G().trim().min(1).optional(),reasoningEffort:Fa.optional(),execution:Lc.optional()});var zc=q({mode:Pc,model:Nc,reasoningEffort:Fa.nullable(),execution:Lc.optional()});q({provider:Pa,model:Nc,reasoningEffort:Fa.nullable(),execution:Lc.optional()});var Bc=q({model:Nc,reasoningEffort:Fa.nullable(),execution:Lc.optional(),context:Rc.optional()}),Vc=q({target:tr(`type`,[q({type:J(`uncommittedChanges`)}),q({type:J(`baseBranch`),branch:G().trim().min(1)}),q({type:J(`commit`),sha:G().trim().min(1),title:G().trim().min(1).optional()}),q({type:J(`custom`),instructions:G().trim().min(1)})])}),Hc=q({preset:Y([`general`,`security`,`performance`,`style`]),scope:Y([`workingTree`,`staged`,`selection`,`custom`]).optional(),instructions:G().trim().min(1).optional()}),Uc=q({provider:Pa,codex:Vc.optional(),claude:Hc.optional()}).superRefine((e,t)=>{if(e.provider===`codex`){e.codex||t.addIssue({code:U.custom,path:[`codex`],message:`codex review config is required when provider is codex`}),e.claude&&t.addIssue({code:U.custom,path:[`claude`],message:`claude review config must be omitted when provider is codex`});return}e.claude||t.addIssue({code:U.custom,path:[`claude`],message:`claude review config is required when provider is claude`}),e.codex&&t.addIssue({code:U.custom,path:[`codex`],message:`codex review config must be omitted when provider is claude`})}),Wc=q({v:J(`1.0`),provider:Pa,sessionId:G().min(1),projectId:G().min(1).optional(),eventId:G().min(1),ts:G().datetime(),type:G().min(1),payload:q({raw:Qn()}).passthrough()}).passthrough(),Gc=Y([`compact`,`full`]),Kc=q({commandId:G().min(1).optional()}),qc=Kc.extend({type:J(`session.start`),payload:q({provider:Pa,model:G().min(1).optional(),projectId:G().min(1).optional(),cwd:G().min(1).optional(),sessionConfig:Va.optional(),sessionTurnConfig:zc.optional(),metadata:nr(Qn()).optional()})}),Jc=Kc.extend({type:J(`turn.input`),payload:q({sessionId:G().min(1),text:G().optional(),attachments:$n(so).max(5).optional(),model:G().min(1).optional(),sessionConfig:Va.optional(),mode:Pc.optional(),config:Bc.optional()}).superRefine((e,t)=>{let n=typeof e.text==`string`&&e.text.trim().length>0,r=(e.attachments?.length??0)>0;!n&&!r&&t.addIssue({code:U.custom,path:[`text`],message:`turn.input requires text or at least one attachment`})})}),Yc=Kc.extend({type:J(`review.start`),payload:q({sessionId:G().min(1),input:G().min(1).optional(),config:Uc,turnConfig:Bc})}),Xc=Kc.extend({type:J(`tool.approval.respond`),payload:q({sessionId:G().min(1),requestId:G().min(1),decision:Y([`allow`,`deny`]),reason:G().min(1).optional()})}),Zc=Kc.extend({type:J(`user.input.respond`),payload:q({sessionId:G().min(1),requestId:G().min(1),answers:nr($n(G()))})}),Qc=Kc.extend({type:J(`session.interrupt`),payload:q({sessionId:G().min(1)})}),$c=Kc.extend({type:J(`session.close`),payload:q({sessionId:G().min(1)})}),el=tr(`kind`,[q({kind:J(`all`)}),q({kind:J(`raw_seq`),rawSeq:K().int().nonnegative()})]),tl=q({sessionId:G().min(1),projectId:G().min(1).optional(),cursor:el,purpose:Y([`detail_view`,`live_follow`]).optional(),detailLevel:Gc.optional(),bootstrapMode:Y([`stream`,`readable`]).optional()}),nl=Kc.extend({type:J(`session.stream.subscribe`),payload:q({replace:Zn().default(!0),sessions:$n(tl)})}),rl=q({sessionId:G().min(1),projectId:G().min(1).optional()}),il=tr(`type`,[qc,Jc,Yc,Xc,Zc,Qc,$c,Kc.extend({type:J(`session.external.watch.set`),payload:q({replace:Zn().default(!0),sessions:$n(rl)})}),nl,Kc.extend({type:J(`fs.read`),payload:q({sessionId:G().min(1),path:G().min(1)})}),Kc.extend({type:J(`fs.diff`),payload:q({sessionId:G().min(1),path:G().min(1),baseContent:G().optional()})})]);function al(e){let t=il.parse(e);if(t.type===`session.start`&&!t.payload.projectId&&!t.payload.cwd)throw Error(`session.start requires at least one of projectId or cwd`);return t}function ol(e,t){if(!Array.isArray(e.content))return;let n=[];for(let r of e.content){let e=t(r);e&&n.push(e)}return n.length>0?n.join(`
136
136
  `):void 0}var sl=q({inputTokens:K().int().nonnegative(),cachedInputTokens:K().int().nonnegative(),outputTokens:K().int().nonnegative(),reasoningOutputTokens:K().int().nonnegative(),totalTokens:K().int().nonnegative()}),cl=q({usedPercent:K(),windowMinutes:K().int().nonnegative().nullable(),resetsAt:K().nonnegative().nullable()}),ll=q({primary:cl.nullable().optional(),secondary:cl.nullable().optional(),planType:G().min(1).nullable().optional(),creditsBalance:G().min(1).nullable().optional()}),ul=q({provider:Pa,usage:q({currentUsage:sl,latestTurnUsage:sl.nullable(),contextWindow:K().int().nonnegative().nullable(),sourceLabel:G().min(1),note:G().min(1).optional()}).nullable(),rateLimits:ll.optional()});function dl(e){return e.provider===`claude`?pl(e.rawEvents):fl(e.rawEvents)}function fl(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null;for(let c of El(e)){let e=jl(c.payload.raw),l=c.type===`native.raw`?ml(e):null;l?.usage&&((Cl(l.usage)||!t)&&(t=l.usage),wl(l.usage.latestTurnUsage)?n=l.usage.latestTurnUsage:wl(l.usage.currentUsage)&&!n&&(n=l.usage.currentUsage),r=l.usage.contextWindow??r),l?.rateLimits&&(i=l.rateLimits.primary??i,a=l.rateLimits.secondary??a,o=l.rateLimits.planType??o,s=l.rateLimits.creditsBalance??s);let u=hl(c);if(u){let e=u.latestTurnUsage??u.currentUsage;wl(e)&&(n=e),r=u.contextWindow??r,!t&&(Cl(u)||u.contextWindow)&&(t=u)}}let c=t?{...t,latestTurnUsage:wl(n)?n:wl(t.latestTurnUsage)?t.latestTurnUsage:wl(t.currentUsage)?t.currentUsage:null,contextWindow:t.contextWindow??r}:null,l=_l({primary:i,secondary:a,planType:o,creditsBalance:s});return!c&&!l?null:{provider:`codex`,usage:c,...l?{rateLimits:l}:{}}}function pl(e){let t=null;for(let n of El(e)){let e=hl(n);e&&(t=e)}return t?{provider:`claude`,usage:t}:null}function ml(e){if(e.source===`codex.history.thread_read`){let t=jl(e.message),n=jl(t.turn),r=bl(n.usage??t.usage),i=kl(n.model_context_window??t.model_context_window);return!r&&i===void 0?null:{usage:{currentUsage:r??Tl(),latestTurnUsage:r??null,contextWindow:i??null,sourceLabel:`codex.history.thread_read`,note:`当前来自 Codex history replay 快照。`}}}let t=Dl(e);if(!t)return null;let n=jl(jl(e.message).params);if(t===`thread/tokenUsage/updated`){let e=jl(n.tokenUsage??n.token_usage),t=bl(e.total??e.total_token_usage);return t?{usage:{currentUsage:t,latestTurnUsage:bl(e.last??e.last_token_usage),contextWindow:kl(e.modelContextWindow??e.model_context_window)??null,sourceLabel:`thread/tokenUsage/updated`}}:null}if(t===`account/rateLimits/updated`){let e=gl(n.rateLimits??n.rate_limits);return e?{rateLimits:e}:null}if(t===`codex/event/token_count`){let e=jl(n.msg),t=jl(e.info),r=bl(t.total_token_usage??t.totalTokenUsage),i=gl(e.rate_limits??e.rateLimits);return!r&&!i?null:{usage:r?{currentUsage:r,latestTurnUsage:bl(t.last_token_usage??t.lastTokenUsage),contextWindow:kl(t.model_context_window??t.modelContextWindow)??null,sourceLabel:`codex/event/token_count`}:void 0,...i?{rateLimits:i}:{}}}if(t===`codex/event/task_started`){let e=jl(n.msg),t=kl(e.model_context_window??e.modelContextWindow);return t===void 0?null:{usage:{currentUsage:Tl(),latestTurnUsage:null,contextWindow:t,sourceLabel:`codex/event/task_started`,note:`目前只拿到了 context window,尚未拿到 thread token usage 快照。`}}}return null}function hl(e){if(e.type!==`turn.completed`&&e.type!==`turn.failed`&&e.type!==`turn.started`)return null;let t=jl(e.payload.raw),n=yl(t.usage??jl(t.turn).usage),r=kl(t.model_context_window??jl(t.turn).model_context_window);return!n&&r===void 0?null:{currentUsage:n??Tl(),latestTurnUsage:n??null,contextWindow:r??null,sourceLabel:e.type}}function gl(e){let t=jl(e),n=vl(t.primary),r=vl(t.secondary),i=Al(t.plan_type??t.planType)??null,a=Al(jl(t.credits).balance)??null;return!n&&!r&&!i&&!a?null:{primary:n,secondary:r,planType:i,creditsBalance:a}}function _l(e){if(!(!e.primary&&!e.secondary&&!e.planType&&!e.creditsBalance))return{...e.primary?{primary:e.primary}:{},...e.secondary?{secondary:e.secondary}:{},...e.planType?{planType:e.planType}:{},...e.creditsBalance?{creditsBalance:e.creditsBalance}:{}}}function vl(e){let t=jl(e),n=kl(t.used_percent??t.usedPercent);return n===void 0?null:{usedPercent:n,windowMinutes:kl(t.window_minutes??t.windowDurationMins)??null,resetsAt:kl(t.resets_at??t.resetsAt)??null}}function yl(e){return xl(e)}function bl(e){return xl(e,{totalFallback:`input_plus_output`})}function xl(e,t){let n=jl(e),r=kl(n.input_tokens??n.inputTokens),i=kl(n.cached_input_tokens??n.cachedInputTokens??n.cache_read_input_tokens??n.cacheReadInputTokens),a=kl(n.output_tokens??n.outputTokens),o=kl(n.reasoning_output_tokens??n.reasoningOutputTokens)??0,s=kl(n.total_tokens??n.totalTokens)??Sl(r,i,a,o,t);return r===void 0&&i===void 0&&a===void 0&&s===void 0?null:{inputTokens:r??0,cachedInputTokens:i??0,outputTokens:a??0,reasoningOutputTokens:o,totalTokens:s??0}}function Sl(e,t,n,r,i){return i?.totalFallback===`input_plus_output`?Ol(e,n):Ol(e,t,n,r)}function Cl(e){return wl(e.latestTurnUsage)||wl(e.currentUsage)}function wl(e){return e?e.inputTokens>0||e.cachedInputTokens>0||e.outputTokens>0||e.reasoningOutputTokens>0||e.totalTokens>0:!1}function Tl(){return{inputTokens:0,cachedInputTokens:0,outputTokens:0,reasoningOutputTokens:0,totalTokens:0}}function El(e){return[...e].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.rawSeq-t.rawSeq:n})}function Dl(e){return Al(jl(e.message).method)??Al(e.method)??null}function Ol(...e){let t=e.filter(e=>typeof e==`number`);if(t.length!==0)return t.reduce((e,t)=>e+t,0)}function kl(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`bigint`)return Number(e);if(typeof e==`string`&&e.trim()){let t=Number(e);if(Number.isFinite(t))return t}}function Al(e){return typeof e==`string`&&e.trim()?e:void 0}function jl(e){return typeof e==`object`&&e?e:{}}var Ml=Y([`session.started`,`thread.started`,`thread.title.updated`,`turn.started`,`turn.completed`,`turn.failed`,`item.started`,`item.updated`,`item.completed`,`tool.permission.requested`,`tool.permission.resolved`,`user.input.requested`,`user.input.resolved`,`file.changed`,`file.diff.ready`,`status.progress`,`error`,`error.runtime`]),Nl=Wc.extend({type:Ml}),Pl=Wc.extend({kind:J(`provider.raw`),rawSeq:K().int().positive(),type:G().min(1)});Nl.extend({kind:J(`gateway.control`).optional(),derivedFrom:G().min(1).optional()});var Fl=Wc.extend({kind:J(`session.stream.sync`),type:J(`session.stream.sync`),payload:q({raw:q({decision:Y([`delta`,`snapshot`]),reason:G().min(1),snapshotId:G().min(1).optional(),fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional()}).passthrough()}).passthrough()}),Il=q({updatedAt:G().datetime().optional(),status:Y([`running`,`idle`]).optional(),interactionLockReason:Y([`external_turn_running`]).optional(),model:G().min(1).nullable().optional(),sessionTurnConfig:zc.optional(),sessionTurnConfigUpdatedAt:G().datetime().optional(),title:G().min(1).optional(),pendingApprovals:K().int().nonnegative().optional(),pendingUserInputs:K().int().nonnegative().optional(),pendingActions:K().int().nonnegative().optional()}),Ll=er([Pl,Fl,Wc.extend({kind:J(`session.stream.snapshot.chunk`),type:J(`session.stream.snapshot.chunk`),payload:q({raw:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),events:$n(Pl),sessionSummary:Il.optional()}).passthrough(),readable:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),timelineItems:$n(Ho).optional(),sessionSummary:Il.optional()}).passthrough().optional()}).passthrough()}),Wc.extend({kind:J(`session.readable.snapshot.chunk`),type:J(`session.readable.snapshot.chunk`),payload:q({readable:q({snapshotId:G().min(1),chunkIndex:K().int().nonnegative(),totalChunks:K().int().positive(),timelineItems:$n(Ho),pendingApprovals:$n(Ro).optional(),pendingUserInputs:$n(Vo).optional(),contextUsage:ul.nullable().optional(),sessionSummary:Il.optional()}).passthrough()}).passthrough()}),Wc.extend({kind:J(`session.readable.delta`),type:J(`session.readable.delta`),payload:q({readable:q({fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative(),timelineUpserts:$n(Ho),timelineRemovals:$n(G().min(1)),timelineTextDeltaPatches:$n(Tc).optional(),pendingApprovalUpserts:$n(Ro).optional(),pendingApprovalRemovals:$n(G().min(1)).optional(),pendingUserInputUpserts:$n(Vo).optional(),pendingUserInputRemovals:$n(G().min(1)).optional(),sessionSummary:Il.optional(),contextUsage:ul.nullable().optional()}).passthrough()}).passthrough()}),Wc.extend({kind:J(`session.external.update`),type:J(`session.external.update`),payload:q({raw:q({updatedAt:G().datetime(),status:Y([`running`,`idle`]),interactionLockReason:Y([`external_turn_running`]).optional(),refreshMode:Y([`delta`,`snapshot`]),fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional(),historyUpdated:Zn(),statusChanged:Zn(),sessionSummary:Il.optional()}).passthrough()}).passthrough()})]),Rl=q({algorithm:Y([`ed25519`]),publicKey:qa,publicKeyFingerprint:G().min(1),keyVersion:K().int().min(1),createdAt:G().datetime()});q({code:G().min(4),expiresAt:G().datetime()});var zl=Y([`ed25519`]),Bl=Y([`active`,`revoked`,`rotating`,`unknown`]),Vl=q({algorithm:zl,publicKey:qa,publicKeyFingerprint:G().min(1)}),Hl=q({pairingCode:G().min(4),signedAt:G().datetime()}),Ul=q({gatewayId:G().min(1),deviceId:G().min(1),mobilePublicKey:qa,pairingContext:Hl}),Wl=q({algorithm:J(`ed25519`),gatewayPublicKeyFingerprint:G().min(1),payload:Ul,signature:qa}),Gl=q({code:G().min(4),deviceName:rr(e=>{if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:void 0},G().min(1).optional()),deviceIdentity:Vl.optional()}),Kl=q({accessToken:G().min(1),refreshToken:G().min(1),expiresInSeconds:K().int().positive()}),ql=Kl.extend({gatewayId:G().min(1),gatewayName:G().min(1).optional(),machineName:G().min(1).optional(),deviceId:G().min(1),gatewayIdentity:Rl.optional(),deviceIdentityFingerprint:G().min(1).optional(),deviceIdentityStatus:Bl.optional(),pairingConfirmation:Wl.optional()}),Jl=q({refreshToken:G().min(1)}),Yl=Kl.extend({deviceId:G().min(1),deviceIdentityFingerprint:G().min(1).optional(),deviceIdentityStatus:Bl.optional()});function Xl(e){return JSON.stringify([e.gatewayId,e.deviceId,e.mobilePublicKey,e.pairingContext.pairingCode,e.pairingContext.signedAt])}var Zl=Y([`missing`,`current`,`stale`]),Ql=q({accountId:G().min(1),accountType:Y([`chatgpt`,`apiKey`,`unknown`]),authMode:G().min(1),planType:G().min(1).nullable(),lastRefreshAt:G().datetime().nullable(),hasSavedSnapshot:Zn(),snapshotStatus:Zl,rateLimits:ll.nullable()}),$l=q({accountId:G().min(1),accountType:Y([`chatgpt`,`apiKey`,`unknown`]),authMode:G().min(1),planType:G().min(1).nullable(),lastRefreshAt:G().datetime().nullable(),savedAt:G().datetime(),isCurrent:Zn(),rateLimits:ll.nullable()}),eu=q({current:Ql.nullable(),savedAccounts:$n($l)}),tu=q({saved:J(!0),accounts:eu}),nu=q({switched:J(!0),closedRuntimeSessionCount:K().int().nonnegative(),accounts:eu}),ru=q({deleted:J(!0),accounts:eu}),iu=q({restarted:J(!0),closedRuntimeSessionCount:K().int().nonnegative()}),au=15e3,ou=12e4;function su(e){return{sessionId:e,messages:new Map,itemToMessageKey:new Map,requestToMessageKey:new Map,turnToLastToolMessageKey:new Map,codexSemanticMessageKeyToMessageKeys:new Map,codexHistoryReplaySemanticOccurrenceByKey:new Map}}function cu(e,t,n=`codex`){if(t.sessionId!==e.sessionId)return;let r=`optimistic:${t.id}`;e.messages.has(r)||e.messages.set(r,{id:r,sessionId:e.sessionId,provider:n,kind:`user`,status:`completed`,ts:t.ts,updatedAt:t.ts,source:`optimistic`,title:`User`,text:t.text,details:[],debug:{eventTypes:[`optimistic.prompt`]}})}function lu(e,t){if(t.sessionId===e.sessionId){if(t.type===`item.started`||t.type===`item.updated`||t.type===`item.completed`){pu(e,t);return}if(t.type===`tool.permission.requested`||t.type===`tool.permission.resolved`){mu(e,t);return}if(t.type===`user.input.requested`||t.type===`user.input.resolved`){hu(e,t);return}if(t.type===`turn.completed`){vu(e,t);return}(t.type===`turn.failed`||t.type===`error`||t.type===`error.runtime`)&&yu(e,t)}}function uu(e){return[...e.messages.values()].map(vd).sort((e,t)=>{let n=e.ts.localeCompare(t.ts);return n===0?e.id.localeCompare(t.id):n})}function du(e,t,n){let r=su(e),i=t[0]?.provider??`codex`,a=[...n].sort((e,t)=>e.ts.localeCompare(t.ts));for(let e of a)cu(r,e,i);let o=[...t].filter(t=>t.sessionId===e).sort((e,t)=>e.ts.localeCompare(t.ts));for(let e of o)lu(r,e);return r}function fu(e,t,n){return uu(du(e,t,n))}function pu(e,t){let n=id(t.payload.raw),r=id(n.item),i=Fu(r,[`type`]),a=Fu(r,[`phase`]),o=Nu(n,r),s=Fu(r,[`id`]),c=Xu(Fu(r,[`status`])),l=Ru(r,i)??Pu(r),u=[...Iu(r),...zu(r,i)],d=wu(t.provider,o,i,a,l,u),f=d?Ou(n):void 0,p=Mu(n)&&d?Eu(e,d,f):void 0;if(!i){let r=Pu(n);if(!r)return;let i=xu(t,`assistant`,o),a=bu(e,i,{id:i,sessionId:e.sessionId,provider:t.provider,kind:`assistant`,status:`streaming`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Assistant`,details:[],turnId:o,debug:{eventTypes:[]}});t.type===`item.completed`?(a.status=`completed`,a.text=r):(a.status=`streaming`,a.text=sd(a.text,r)),gd(a,t);return}let m=Cu(i);if(m===`user`&&!l&&u.length===0)return;let h=p??(s?`item:${s}`:xu(t,i,o)),g=Su(m,i),_=m===`tool`?rd(r,l):void 0,v=bu(e,h,{id:h,sessionId:e.sessionId,provider:t.provider,kind:m,status:`streaming`,ts:t.ts,updatedAt:t.ts,source:`event`,title:g,details:[],itemType:i,itemId:s,turnId:o,collapsible:m===`reasoning`,collapsedByDefault:m===`reasoning`,debug:{eventTypes:[],rawItemType:i,...a?{rawItemPhase:a}:{}}});s&&e.itemToMessageKey.set(s,h),d&&Tu(e,d,h),o&&m===`tool`&&e.turnToLastToolMessageKey.set(o,h),v.provider=t.provider,v.itemType=i,v.debug.rawItemPhase=a??v.debug.rawItemPhase,p&&v.itemId&&s&&v.itemId!==s||(v.itemId=s??v.itemId),v.turnId=o??v.turnId,v.title=_?.title??g,v.updatedAt=t.ts,v.collapsible=m===`reasoning`,v.collapsedByDefault=m===`reasoning`,_&&(v.toolCardData=_),u.length>0&&(v.attachments=qu(v.attachments,u));let y=Fu(r,[`source_event_type`]);if(y&&ju(m)&&!_&&md(v,`source: ${y}`),m===`tool`&&!_)for(let e of hd(r))md(v,e);t.type===`item.started`?(v.status=m===`user`?`completed`:`streaming`,l&&(v.text=cd(m)?ld(v.text,l,r):sd(v.text,l))):t.type===`item.updated`?(v.status=m===`user`?`completed`:v.status===`waiting_approval`||v.status===`waiting_input`?v.status:`streaming`,l&&(v.text=cd(m)?ld(v.text,l,r):sd(v.text,l))):t.type===`item.completed`&&(v.status=m===`error`?`failed`:c??`completed`,l&&(v.text=l)),gd(v,t),d&&Mu(n)&&Du(e,d,f),m===`user`&&v.text&&_d(e,v.text,v.ts)}function mu(e,t){let n=id(t.payload.raw),r=Fu(n,[`requestId`,`request_id`]);if(!r)return;let i=Fu(n,[`itemId`,`item_id`]),a=Fu(n,[`turnId`,`turn_id`]),o=Fu(n,[`toolName`,`tool_name`])??`tool`,s=Fu(n,[`reason`]),c=Fu(n,[`decision`]),l=id(n.rawParams??n.raw_params),u=id(l.networkApprovalContext??l.network_approval_context),d=Fu(l,[`command`]),f=Fu(l,[`cwd`]),p=Fu(l,[`grantRoot`,`grant_root`]),m=Fu(u,[`host`]),h=Fu(u,[`protocol`]),g=gu(e,r,`approval`),_=bu(e,g,{id:g,sessionId:e.sessionId,provider:t.provider,kind:`tool`,status:`waiting_approval`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Tool Approval`,details:[],itemType:`tool_status`,itemId:i??void 0,turnId:a??void 0,requestId:r,debug:{eventTypes:[],rawItemType:`tool_status`}});_.provider=t.provider,_.updatedAt=t.ts,_.requestId=r,_.itemId=i??_.itemId,_.turnId=a??_.turnId,_.title=_.title||`Tool Approval`,t.type===`tool.permission.requested`?(_.status=`waiting_approval`,_.text=d?`等待命令执行审批`:`${o} \u9700\u8981\u5BA1\u6279`,md(_,`tool: ${o}`),s&&md(_,`reason: ${s}`),d&&md(_,`command: ${xd(d,200)}`),f&&md(_,`cwd: ${xd(f,200)}`),p&&md(_,`grant_root: ${xd(p,200)}`),m&&md(_,`network: ${xd(h?`${h}://${m}`:m,200)}`)):(_.status=c===`deny`?`failed`:`completed`,_.text=c===`deny`?`工具审批已拒绝`:`工具审批已通过`,c&&md(_,`decision: ${c}`),s&&md(_,`reason: ${s}`)),_u(e,g,r,i,a),gd(_,t)}function hu(e,t){let n=id(t.payload.raw),r=Fu(n,[`requestId`,`request_id`]);if(!r)return;let i=Fu(n,[`itemId`,`item_id`]),a=Fu(n,[`turnId`,`turn_id`]),o=Fu(n,[`status`]),s=Fu(n,[`reason`]),c=ed(n,[`answeredCount`,`answered_count`]),l=td(n.questions),u=nd(n.answers),d=gu(e,r,`user-input`),f=bu(e,d,{id:d,sessionId:e.sessionId,provider:t.provider,kind:`tool`,status:`waiting_input`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Plan Question`,details:[],itemType:`request_user_input`,itemId:i??void 0,turnId:a??void 0,requestId:r,userInputQuestions:l,debug:{eventTypes:[],rawItemType:`request_user_input`}});if(f.provider=t.provider,f.updatedAt=t.ts,f.requestId=r,f.itemId=i??f.itemId,f.turnId=a??f.turnId,f.title=`Plan Question`,t.type===`user.input.requested`)f.status=`waiting_input`,f.text=l.length>0?`\u9700\u8981\u56DE\u7B54 ${l.length} \u4E2A\u95EE\u9898`:`需要回答问题`,f.userInputQuestions=l,f.userInputAnswers=void 0,md(f,`request_id: ${r}`);else{f.status=Zu(o);let e=c??0;f.text=Qu(o,e),md(f,`status: ${o??`submitted`}`),md(f,`answered_count: ${e}`),s&&md(f,`reason: ${s}`),l.length>0&&(f.userInputQuestions=l),u&&(f.userInputAnswers=u)}_u(e,d,r,i,a),gd(f,t)}function gu(e,t,n){return e.requestToMessageKey.get(t)??`${n}:${t}`}function _u(e,t,n,r,i){e.requestToMessageKey.set(n,t),r&&e.itemToMessageKey.set(r,t),i&&e.turnToLastToolMessageKey.set(i,t)}function vu(e,t){let n=id(t.payload.raw),r=Nu(n,void 0),i=id(n.usage),a=id(id(n.turn).usage),o=ed(i,[`input_tokens`]),s=ed(i,[`output_tokens`]),c=ed(a,[`input_tokens`]),l=ed(a,[`output_tokens`]),u=o??c,d=s??l;if(r)for(let n of e.messages.values())n.turnId===r&&n.status===`streaming`&&(n.status=`completed`,n.updatedAt=t.ts);if(u!==void 0||d!==void 0){let n=r?`turn-usage:${r}`:xu(t,`turn.usage`,r),i=bu(e,n,{id:n,sessionId:e.sessionId,provider:t.provider,kind:`system`,status:`completed`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Turn Usage`,details:[],turnId:r,debug:{eventTypes:[]}});i.provider=t.provider,i.status=`completed`,i.updatedAt=t.ts,i.text=`Token usage`,u!==void 0&&md(i,`input_tokens: ${u}`),d!==void 0&&md(i,`output_tokens: ${d}`),gd(i,t)}}function yu(e,t){let n=id(t.payload.raw),r=Pu(id(n.error))??Pu(n);if(!r)return;let i=Nu(n,void 0),a=i?`turn-error:${i}`:`error:${t.eventId}`,o=bu(e,a,{id:a,sessionId:e.sessionId,provider:t.provider,kind:`error`,status:`failed`,ts:t.ts,updatedAt:t.ts,source:`event`,title:`Error`,text:r,details:[],turnId:i,debug:{eventTypes:[]}});o.provider=t.provider,o.status=`failed`,o.updatedAt=t.ts,o.text=r,o.turnId=i??o.turnId,gd(o,t)}function bu(e,t,n){return e.messages.get(t)||(e.messages.set(t,n),n)}function xu(e,t,n){let r=Date.parse(e.ts),i=Number.isFinite(r)?Math.floor(r/au):Math.floor(Cd(e.ts)/au);return`fallback:${e.provider}:${n??`no_turn`}:${t}:${i}`}function Su(e,t){return t===`plan`?`Plan`:e===`assistant`?t===`image_generation`||t===`image_view`?`Image`:`Assistant`:e===`user`?`User`:e===`tool`?t===`command_execution`?`Command`:t===`file_change`?`File Change`:t===`mcp_tool_call`?`MCP Tool`:t===`web_search`?`Web Search`:`Tool`:e===`reasoning`?t===`todo_list`?`Todo`:t===`plan`?`Plan`:`Reasoning`:e===`error`?`Error`:`System`}function Cu(e){return e===`user_message`?`user`:e===`agent_message`||e===`plan`||e===`image_generation`||e===`image_view`?`assistant`:e===`command_execution`||e===`file_change`||e===`mcp_tool_call`||e===`web_search`||e===`tool_status`||e===`collab_tool_call`?`tool`:e===`reasoning`||e===`todo_list`?`reasoning`:e===`error`?`error`:`system`}function wu(e,t,n,r,i,a){let o=Ju(a);if(e!==`codex`||!t||!i&&!o)return;let s=ku(n);if(!(s!==`user_message`&&s!==`agent_message`))return`${t}|${s}|${Au(s,r)}|${i??``}|${o}`}function Tu(e,t,n){let r=e.codexSemanticMessageKeyToMessageKeys.get(t);if(!r){e.codexSemanticMessageKeyToMessageKeys.set(t,[n]);return}r.includes(n)||r.push(n)}function Eu(e,t,n){let r=e.codexSemanticMessageKeyToMessageKeys.get(t);if(!(!r||r.length===0))return r[n===void 0?e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0:n-1]}function Du(e,t,n){let r=n??(e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0)+1,i=e.codexHistoryReplaySemanticOccurrenceByKey.get(t)??0;e.codexHistoryReplaySemanticOccurrenceByKey.set(t,Math.max(i,r))}function Ou(e){let t=e.semantic_occurrence??e.semanticOccurrence;if(typeof t==`number`&&Number.isInteger(t)&&t>0)return t;if(typeof t==`string`){let e=Number.parseInt(t,10);if(Number.isInteger(e)&&e>0)return e}}function ku(e){if(!e)return;let t=e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).replace(/[\s-]+/g,`_`).toLowerCase();return t.length>0?t:void 0}function Au(e,t){return e===`agent_message`&&(!t||t===`final_answer`)?``:t??``}function ju(e){return e===`tool`}function Mu(e){if(e.historyReplay===!0)return!0;let t=Fu(e,[`source`]);return t===`codex.history.thread_read`||t===`codex.history.thread_read.incremental`}function Nu(e,t){return Fu(e,[`turn_id`,`turnId`])??Fu(id(e.turn),[`id`,`turn_id`,`turnId`])??Fu(t??{},[`turn_id`,`turnId`])}function Pu(e){return $u(id(e.payload),[`delta`,`output_delta`,`outputDelta`])||$u(e,[`text`,`message`,`output`,`response`,`reason`,`output_delta`,`aggregated_output`])||ad(e)}function Fu(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.trim())return t}}function Iu(e){return[...Lu(e.attachments),...Lu(e.content),...Lu(e.input)]}function Lu(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=id(n),r=id(e.remote_agent_attachment),i=Fu(e,[`type`]),a=Fu(e,[`kind`]),o=id(e.source),s=id(r.locator),c=Fu(e,[`path`])??Fu(o,[`path`])??Fu(s,[`path`]),l=Uu(Fu(r,[`mimeType`,`mime_type`])??Fu(e,[`mimeType`,`mime_type`])??Fu(o,[`media_type`,`mediaType`]));if(i!==`image`&&i!==`localImage`&&i!==`local_image`&&a!==`image`&&!c&&Object.keys(r).length===0)continue;let u=Fu(r,[`id`])??Fu(e,[`id`])??c??`image-${t.length+1}`;t.push({id:u,kind:`image`,...l?{mimeType:l}:{},fileName:Fu(r,[`fileName`,`file_name`])??Fu(e,[`fileName`,`file_name`]),width:Gu(r.width??e.width),height:Gu(r.height??e.height),sizeBytes:Ku(r.sizeBytes??r.size_bytes??e.sizeBytes??e.size_bytes),...c?{locator:{kind:`absolute`,path:c}}:{}})}return t}function Ru(e,t){let n=Bu(e,t);if(n)return`![Generated image](${Vu(n)})`}function zu(e,t){let n=Bu(e,t);if(!n)return[];let r=Fu(e,[`id`])??n,i=Uu(Fu(e,[`mime_type`,`mimeType`]))??Wu(n),a=Hu(n);return[{id:r,kind:`image`,...i?{mimeType:i}:{},...a?{fileName:a}:{},locator:{kind:`absolute`,path:n}}]}function Bu(e,t){let n=ku(t);if(n===`image_generation`)return Fu(e,[`saved_path`,`savedPath`,`path`]);if(n===`image_view`)return Fu(e,[`path`,`saved_path`,`savedPath`])}function Vu(e){let t=e.trim();return t?/[\s()<>]/.test(t)?`<${t.replace(/</g,`%3C`).replace(/>/g,`%3E`)}>`:t:``}function Hu(e){let t=e.split(/[\\/]/).filter(Boolean).pop();return t&&t.trim()?t:void 0}function Uu(e){if(e===`image/png`||e===`image/jpeg`||e===`image/webp`)return e}function Wu(e){let t=e.toLowerCase();if(t.endsWith(`.png`))return`image/png`;if(t.endsWith(`.jpg`)||t.endsWith(`.jpeg`))return`image/jpeg`;if(t.endsWith(`.webp`))return`image/webp`}function Gu(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0}function Ku(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.round(e):void 0}function qu(e,t){let n=new Map;for(let r of[...e??[],...t])n.set(Yu(r),r);return[...n.values()]}function Ju(e){return!e||e.length===0?``:e.map(Yu).sort().join(`,`)}function Yu(e){return e.locator?.kind===`absolute`?`path:${e.locator.path}`:`id:${e.id}`}function Xu(e){if(e===`streaming`||e===`waiting_approval`||e===`waiting_input`||e===`completed`||e===`failed`)return e;if(e===`running`)return`streaming`}function Zu(e){return!e||e===`submitted`?`completed`:`failed`}function Qu(e,t){return!e||e===`submitted`?`\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:e===`interrupted`?t>0?`\u5DF2\u4E2D\u65AD\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已中断`:e===`cancelled`?t>0?`\u5DF2\u53D6\u6D88\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已取消`:e===`expired`?t>0?`\u5DF2\u8FC7\u671F\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已过期`:e===`dismissed`?t>0?`\u5DF2\u5173\u95ED\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问已关闭`:t>0?`\u672A\u5B8C\u6210\uFF0C\u5DF2\u63D0\u4EA4 ${t} \u9879\u56DE\u7B54`:`未回答,提问未完成`}function $u(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}function ed(e,t){for(let n of t){let t=e[n];if(typeof t==`number`&&Number.isFinite(t))return t}}function td(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=id(n),r=Fu(e,[`id`]),i=Fu(e,[`header`]),a=Fu(e,[`question`]);if(!r||!i||!a)continue;let o=Array.isArray(e.options)?e.options.map(e=>{let t=id(e),n=Fu(t,[`label`]),r=Fu(t,[`description`])??n,i=Fu(t,[`markdown`]);return n?{label:n,description:r,...i?{markdown:i}:{}}:null}).filter(e=>e!==null):null;t.push({id:r,header:i,question:a,multiSelect:e.multiSelect===!0,isOther:e.isOther===!0,isSecret:e.isSecret===!0,options:o})}return t}function nd(e){let t=id(e),n=Object.entries(t);if(n.length===0)return;let r={};for(let[e,t]of n)if(e){if(!Array.isArray(t)){r[e]=[];continue}r[e]=t.map(e=>typeof e==`string`?e:void 0).filter(e=>typeof e==`string`&&e.length>0)}return Object.keys(r).length>0?r:void 0}function rd(e,t){if(Fu(e,[`display_as`])!==`tool_card`)return;let n=Fu(e,[`title`])??t,r=Fu(e,[`status_label`])??t;if(!n||!r)return;let i=[],a=Fu(e,[`prompt`]),o=Fu(e,[`response`]),s=Fu(e,[`response_label`])??`Response`;a&&i.push({label:`Prompt`,body:a}),o&&i.push({label:s,body:o});let c=[],l=Fu(e,[`file_path`]),u=ed(e,[`exit_code`,`exitCode`]),d=ed(e,[`total_tool_uses`]),f=ed(e,[`total_tokens`]),p=ed(e,[`duration_ms`]);return l&&c.push(l),typeof u==`number`&&c.push(`exit_code: ${u}`),typeof d==`number`&&c.push(`${d} tool uses`),typeof f==`number`&&c.push(`${yd(f)} tokens`),typeof p==`number`&&c.push(bd(p)),{title:n,statusLabel:r,compactText:t?Sd(t):void 0,sections:i,details:c}}function id(e){return typeof e==`object`&&e?e:{}}function ad(e){return ol(e,od)}function od(e){if(typeof e==`string`&&e.length>0)return e;let t=id(e),n=$u(t,[`text`,`message`,`output`,`response`,`reason`]);if(n)return n;let r=$u(id(t.data),[`text`,`message`,`output`,`response`,`reason`]);if(r)return r;if(!Array.isArray(t.text_elements))return;let i=[];for(let e of t.text_elements){let t=$u(id(e),[`text`,`value`]);t&&i.push(t)}return i.length>0?i.join(``):void 0}function sd(e,t){return!e||t.startsWith(e)?t:e.endsWith(t)?e:`${e}${t}`}function cd(e){return e===`assistant`||e===`reasoning`}function ld(e,t,n){return e?t===e?e:t.startsWith(e)?t:e.endsWith(t)?e:ud(n)?`${e}${t}`:fd(e,t)?t:`${e}${t}`:t}function ud(e){let t=id(e.payload);return pd(t.delta)||pd(t.output_delta)||pd(t.outputDelta)||pd(e.output_delta)||pd(e.outputDelta)?!0:dd(Fu(e,[`original_method`,`originalMethod`]))}function dd(e){return e?e===`item/agentMessage/delta`||e===`codex/event/agent_message_content_delta`:!1}function fd(e,t){return t.length===0||t.length<24?!1:t.length>=Math.floor(e.length*.7)}function pd(e){return typeof e==`string`&&e.length>0}function md(e,t){t.trim()&&(e.details.includes(t)||e.details.push(t))}function hd(e){let t=[],n=Fu(e,[`command`]),r=Fu(e,[`tool_name`,`tool`]),i=Fu(e,[`server`]),a=Fu(e,[`status`]),o=Fu(e,[`query`]),s=Fu(e,[`output_delta`,`aggregated_output`]),c=e.history_output_omitted===!0||e.historyOutputOmitted===!0,l=ed(e,[`history_output_byte_length`,`historyOutputByteLength`]),u=ed(e,[`exit_code`]),d=Fu(id(e.error),[`message`]);if(n&&t.push(`command: ${xd(n,200)}`),r&&t.push(`tool: ${r}`),i&&t.push(`server: ${i}`),a&&t.push(`status: ${a}`),o&&t.push(`query: ${xd(o,200)}`),u!==void 0&&t.push(`exit_code: ${u}`),d&&t.push(`error: ${xd(d,200)}`),s?t.push(`output: ${xd(s,400)}`):c&&t.push(l===void 0?`output: omitted in compact history`:`output: omitted in compact history (${l.toLocaleString(`en-US`)} bytes)`),e.type===`todo_list`){let n=Array.isArray(e.items)?e.items:[];for(let e of n){let n=id(e),r=Fu(n,[`text`])??``,i=n.completed===!0;t.push(`${i?`[x]`:`[ ]`} ${r}`)}}if(e.type===`file_change`){let n=Array.isArray(e.changes)?e.changes:[];for(let e of n){let n=id(e),r=Fu(n,[`path`])??`unknown`,i=Fu(n,[`kind`])??`update`;t.push(`${i}: ${r}`)}}return t}function gd(e,t){e.debug.eventTypes.includes(t.type)||e.debug.eventTypes.push(t.type)}function _d(e,t,n){let r=Sd(t),i=Date.parse(n);for(let[t,n]of e.messages.entries()){if(n.kind!==`user`||n.source!==`optimistic`||Sd(n.text??``)!==r)continue;let a=Date.parse(n.ts);if(!(Number.isFinite(i)&&Number.isFinite(a)&&Math.abs(i-a)>ou)){e.messages.delete(t);return}}}function vd(e){return{...e,attachments:e.attachments?e.attachments.map(e=>({...e,locator:e.locator?{...e.locator}:void 0})):void 0,details:[...e.details],userInputQuestions:e.userInputQuestions?e.userInputQuestions.map(e=>({...e,options:e.options?e.options.map(e=>({...e})):null})):void 0,userInputAnswers:e.userInputAnswers?Object.fromEntries(Object.entries(e.userInputAnswers).map(([e,t])=>[e,[...t]])):void 0,toolCardData:e.toolCardData?{...e.toolCardData,sections:e.toolCardData.sections.map(e=>({...e})),details:[...e.toolCardData.details]}:void 0,debug:{...e.debug,eventTypes:[...e.debug.eventTypes]}}}function yd(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}function bd(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 xd(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function Sd(e){return e.trim().replace(/\s+/g,` `)}function Cd(e){let t=0;for(let n=0;n<e.length;n+=1)t=t*31+e.charCodeAt(n)>>>0;return t}var wd=Y([`unknown`,`checking`,`up_to_date`,`available`,`unsupported_install`,`updating`,`restarting`,`failed`]),Td=Y([`npm`,`pnpm`,`yarn`,`unknown`]),Ed=Y([`global_registry`,`global_file`,`dev_workspace`,`standalone_binary`,`unknown`]),Dd=Y([`console`,`mobile`,`system`]),Od=q({manager:Td,installType:Ed,packageName:G().min(1),packageRoot:G().min(1).optional(),binPath:G().min(1).optional(),canSelfUpdate:Zn(),reason:G().min(1).optional()}),kd=q({id:G().min(1),targetVersion:G().min(1),requestedBy:Dd,requestedAt:G().datetime(),startedAt:G().datetime().optional()}),Ad=q({packageName:G().min(1),currentVersion:G().min(1),latestVersion:G().min(1).optional(),available:Zn(),canApply:Zn(),status:wd,checkedAt:G().datetime().optional(),install:Od,job:kd.optional(),lastError:G().min(1).optional()}),jd=q({type:J(`gateway.update.status`),payload:Ad}),Md=q({started:Zn(),update:Ad}),Nd=rr(e=>{if(typeof e!=`string`)return e;let t=e.trim();return t.length>0?t:e},G().trim().min(1)),Pd=q({id:G().min(1),title:G().min(1),path:G().min(1),createdAt:G().datetime(),updatedAt:G().datetime(),lastSessionAt:G().datetime().optional(),runningCount:K().int().nonnegative(),idleCount:K().int().nonnegative().optional(),totalCount:K().int().nonnegative().optional(),endedCount:K().int().nonnegative()}),Fd=q({name:G().min(1),path:G().min(1)}),Id=q({kind:Y([`home`,`desktop`,`documents`,`downloads`,`root`]),path:G().min(1)}),Ld=q({rootPath:G().min(1),currentPath:G().min(1),parentPath:G().min(1).nullable(),shortcuts:$n(Id).default([]),directories:$n(Fd)}),Rd=Y([`running`,`idle`]),zd=Y([`running`,`idle`,`all`]),Bd=Y([`external_turn_running`]),Vd=Y([`delta`,`snapshot`]),Hd=q({id:G().min(1),nativeSessionId:G().min(1).optional(),source:Y([`gateway`,`native_discovered`]).optional(),projectId:G().min(1),projectPath:G().min(1),provider:Pa,providerMode:Y([`native`,`mock`]).optional(),model:G().min(1).optional(),title:G().min(1).optional(),sessionTurnConfig:zc.optional(),sessionTurnConfigUpdatedAt:G().datetime().optional(),createdAt:G().datetime(),updatedAt:G().datetime(),status:Rd,interactionLockReason:Bd.optional(),pendingApprovals:K().int().nonnegative(),pendingUserInputs:K().int().nonnegative(),pendingActions:K().int().nonnegative()}),Ud=q({id:G().min(1),name:G().min(1),createdAt:G().datetime(),revokedAt:G().datetime().optional(),identityAlgorithm:Y([`ed25519`]).optional(),publicKeyFingerprint:G().min(1).optional(),identityStatus:Bl.optional(),lastVerifiedAt:G().datetime().optional()}),Wd=q({name:Nd,machineName:G().min(1)}),Gd=q({agent:q({provider:Pa,requestedVersion:G().min(1).nullable(),resolvedVersion:G().min(1)}),capabilities:Wa}),Kd=q({scannedAt:G().datetime(),sessionCount:K().int().nonnegative(),status:Y([`ready`,`partial`,`failed`]),error:G().min(1).optional()}),qd=q({codex:Kd.optional(),claude:Kd.optional()}),Jd=q({key:G().min(1),path:G().min(1),title:G().min(1),lastSessionAt:G().datetime().optional(),sessionCount:K().int().nonnegative(),providerCounts:q({codex:K().int().nonnegative(),claude:K().int().nonnegative()}),lastDiscoveryAt:G().datetime()}),Yd=q({provider:Pa,nativeSessionId:G().min(1),title:G().min(1).optional(),model:G().min(1).optional(),createdAt:G().datetime().optional(),updatedAt:G().datetime()}),Xd=q({generatedAt:G().datetime(),source:Y([`cache`,`fresh_scan`]),providers:qd,projects:$n(Jd)}),Zd=q({canonicalProjectPath:G().min(1),project:Jd,providers:qd,sessions:$n(Yd)}),Qd=Y(`auth.refresh,codex.accounts.get,codex.accounts.save,codex.accounts.switch,codex.accounts.delete,codex.appServer.restart,gateway.settings.get,gateway.settings.update,gateway.update.get,gateway.update.apply,projects.list,projects.discovery.get,projects.discovery.refresh,projects.create,projects.delete,workspace.directories.list,workspace.directories.create,workspace.entries.list,workspace.files.resolve,workspace.files.readText,workspace.files.preparePreview,sessions.list,sessions.discovery.list,sessions.get,sessions.config.get,sessions.history.sync,sessions.rawEvents.list,sessions.readableItem.get,providers.capabilities.get,providers.execution.update,agents.config.get,devices.list,devices.revoke`.split(`,`)),$d=q({}).strict(),ef=tr(`method`,[q({method:J(`auth.refresh`),params:Jl.extend({deviceId:G().min(1).optional()})}),q({method:J(`codex.accounts.get`),params:$d}),q({method:J(`codex.accounts.save`),params:$d}),q({method:J(`codex.accounts.switch`),params:q({accountId:G().min(1)})}),q({method:J(`codex.accounts.delete`),params:q({accountId:G().min(1)})}),q({method:J(`codex.appServer.restart`),params:q({requestedBy:Dd.optional()})}),q({method:J(`gateway.settings.get`),params:$d}),q({method:J(`gateway.settings.update`),params:q({name:Nd})}),q({method:J(`gateway.update.get`),params:$d}),q({method:J(`gateway.update.apply`),params:q({requestedBy:Dd.optional()})}),q({method:J(`projects.list`),params:$d}),q({method:J(`projects.discovery.get`),params:$d}),q({method:J(`projects.discovery.refresh`),params:$d}),q({method:J(`projects.create`),params:q({path:Nd,title:G().min(1).optional()})}),q({method:J(`projects.delete`),params:q({projectId:G().min(1)})}),q({method:J(`workspace.directories.list`),params:q({path:G().min(1).optional(),limit:K().int().positive().max(500).optional()})}),q({method:J(`workspace.directories.create`),params:q({path:Nd,name:Nd})}),q({method:J(`workspace.entries.list`),params:q({locator:Ya,limit:K().int().positive().max(500).optional()})}),q({method:J(`workspace.files.resolve`),params:q({locator:Ja})}),q({method:J(`workspace.files.readText`),params:q({locator:Ja,encoding:J(`utf8`).optional(),startLine:K().int().positive().optional(),maxLines:K().int().positive().max(5e3).optional(),maxBytes:K().int().positive().max(1024*1024).optional()})}),q({method:J(`workspace.files.preparePreview`),params:q({locator:Ja,disposition:io.optional()})}),q({method:J(`sessions.list`),params:q({projectId:G().min(1),status:zd.optional(),syncExternal:Zn().optional()})}),q({method:J(`sessions.discovery.list`),params:q({projectPath:Nd})}),q({method:J(`sessions.get`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.config.get`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.history.sync`),params:q({projectId:G().min(1),sessionId:G().min(1)})}),q({method:J(`sessions.rawEvents.list`),params:q({projectId:G().min(1),sessionId:G().min(1),limit:er([K().int().positive().max(2e3),J(`all`)]).optional(),fromRawSeqExclusive:K().int().nonnegative().optional(),detailLevel:Gc.optional()})}),q({method:J(`sessions.readableItem.get`),params:q({projectId:G().min(1),sessionId:G().min(1),itemId:G().min(1)})}),q({method:J(`providers.capabilities.get`),params:q({provider:Pa,projectId:G().min(1).optional(),agentVersion:G().min(1).optional()})}),q({method:J(`providers.execution.update`),params:Ha}),q({method:J(`agents.config.get`),params:q({provider:Pa,projectId:G().min(1).optional(),agentVersion:G().min(1).optional()})}),q({method:J(`devices.list`),params:$d}),q({method:J(`devices.revoke`),params:q({deviceId:G().min(1)})})]),tf=tr(`method`,[q({method:J(`auth.refresh`),result:Yl.extend({relayToken:G().min(1).optional()})}),q({method:J(`codex.accounts.get`),result:eu}),q({method:J(`codex.accounts.save`),result:tu}),q({method:J(`codex.accounts.switch`),result:nu}),q({method:J(`codex.accounts.delete`),result:ru}),q({method:J(`codex.appServer.restart`),result:iu}),q({method:J(`gateway.settings.get`),result:Wd}),q({method:J(`gateway.settings.update`),result:Wd}),q({method:J(`gateway.update.get`),result:Ad}),q({method:J(`gateway.update.apply`),result:Md}),q({method:J(`projects.list`),result:q({projects:$n(Pd)})}),q({method:J(`projects.discovery.get`),result:Xd}),q({method:J(`projects.discovery.refresh`),result:Xd}),q({method:J(`projects.create`),result:q({project:Pd})}),q({method:J(`projects.delete`),result:q({removed:J(!0)})}),q({method:J(`workspace.directories.list`),result:Ld}),q({method:J(`workspace.directories.create`),result:Ld}),q({method:J(`workspace.entries.list`),result:to}),q({method:J(`workspace.files.resolve`),result:no}),q({method:J(`workspace.files.readText`),result:ro}),q({method:J(`workspace.files.preparePreview`),result:ao}),q({method:J(`sessions.list`),result:q({sessions:$n(Hd)})}),q({method:J(`sessions.discovery.list`),result:Zd}),q({method:J(`sessions.get`),result:q({session:Hd})}),q({method:J(`sessions.config.get`),result:q({session:Hd})}),q({method:J(`sessions.history.sync`),result:q({session:Hd,rawEventCount:K().int().nonnegative(),historyUpdated:Zn(),statusChanged:Zn(),refreshMode:Vd,fromRawSeq:K().int().nonnegative().optional(),toRawSeq:K().int().nonnegative().optional()})}),q({method:J(`sessions.rawEvents.list`),result:tr(`decision`,[q({decision:J(`delta`),reason:Y([`cursor_valid_delta`]),fromRawSeqExclusive:K().int().nonnegative(),toRawSeq:K().int().nonnegative(),events:$n(Qn())}),q({decision:J(`snapshot`),reason:Y([`cursor_out_of_range`,`initial_snapshot`,`empty_history_snapshot`]),toRawSeq:K().int().nonnegative().optional(),events:$n(Qn())})])}),q({method:J(`sessions.readableItem.get`),result:q({item:Ho})}),q({method:J(`providers.capabilities.get`),result:q({capabilities:Wa})}),q({method:J(`providers.execution.update`),result:q({defaults:Ha})}),q({method:J(`agents.config.get`),result:Gd}),q({method:J(`devices.list`),result:q({devices:$n(Ud)})}),q({method:J(`devices.revoke`),result:q({revoked:J(!0)})})]),nf=`json-utf8`,rf=Y([nf]),af=Y([`identity`,`gzip`]),of=q({version:J(1),compression:J(`gzip`),payloadEncoding:rf.default(nf),uncompressedByteLength:K().int().positive(),compressedByteLength:K().int().positive(),data:qa});function sf(e){let t=uf(e.payload),n=t.byteLength;if(n<(e.compressionThresholdBytes??1/0))return{payloadEncoding:nf,compression:`identity`,payloadBytes:t,uncompressedByteLength:n,compressedByteLength:n};let r=ni(t);return r.byteLength>=n?{payloadEncoding:nf,compression:`identity`,payloadBytes:t,uncompressedByteLength:n,compressedByteLength:n}:{payloadEncoding:nf,compression:`gzip`,payloadBytes:r,uncompressedByteLength:n,compressedByteLength:r.byteLength}}function cf(e){return e.compression===`gzip`?of.parse({version:1,compression:`gzip`,payloadEncoding:e.payloadEncoding,uncompressedByteLength:e.uncompressedByteLength,compressedByteLength:e.compressedByteLength,data:pf(e.payloadBytes)}):null}function lf(e){let t=af.parse(e.compression??`identity`),n=e.payloadBytes;if(t===`gzip`)try{n=ri(e.payloadBytes)}catch{throw Error(`compressed_payload_invalid`)}if(typeof e.expectedUncompressedByteLength==`number`&&n.byteLength!==e.expectedUncompressedByteLength)throw Error(`compressed_payload_size_mismatch`);let r;try{r=JSON.parse(ff(n))}catch{throw Error(`compressed_payload_invalid`)}return e.parse(r)}function uf(e){return df(JSON.stringify(e))}function df(e){return new TextEncoder().encode(e)}function ff(e){return new TextDecoder().decode(e)}function pf(e){let t=globalThis.Buffer;if(t)return t.from(e).toString(`base64`);let n=``;for(let t of e)n+=String.fromCharCode(t);if(typeof btoa!=`function`)throw Error(`base64 encoder unavailable`);return btoa(n)}var mf=G().url(),hf=er([mf,J(``)]),gf=G().min(1).regex(/^[A-Za-z0-9_-]+$/u),_f=Y([`plaintext-relay`,`e2ee-relay`]),vf=Y([`plain`,`crypt`]);function yf(e){if(e===`plain`||e===`crypt`)return e;if(e===`plaintext-relay`)return`plain`;if(e===`e2ee-relay`)return`crypt`}function bf(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e,n=yf(t.tsl??t.transportSecurityLevel);return n?{...t,tsl:n}:t}function xf(e){return e.trim()}var Sf=Y([`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`]),Cf=K().int().positive(),wf=K().int().min(0).max(2**53-1),Tf=Y([`identity_mismatch`,`device_revoked`,`transcript_invalid`,`counter_replay`,`counter_gap_too_large`,`key_epoch_mismatch`,`decrypt_failed`,`unsupported_version`]),Ef=Y([`guest`,`account`,`self_hosted`]);q({type:J(`relay.gateway`),grantType:Ef,gatewayId:G().min(1),subjectId:G().min(1),gatewayIdentityFingerprint:G().min(1).optional(),jti:G().min(1),iss:G().min(1),aud:G().min(1),iat:K().int().nonnegative(),exp:K().int().positive()}),q({type:J(`relay.mobile`),gatewayId:G().min(1),deviceId:G().min(1),iat:K().int().nonnegative(),exp:K().int().positive()});var Df=q({v:J(1),gw:G().min(1),name:G().min(1),machineName:G().min(1).optional(),relay:hf.optional(),direct:$n(mf).default([]),pc:G().min(1),tsl:vf.optional(),gatewayIdentity:Rl.optional()});rr(bf,Df);var Of=rr(bf,Df.omit({pc:!0}));rr(bf,q({v:J(1),gw:G().min(1),relay:hf.optional(),direct:hf.optional(),pc:G().min(1),tsl:vf.optional(),gatewayIdentity:Rl.optional()}));var kf=rr(bf,q({v:J(1),gw:G().min(1),relay:hf.optional(),direct:mf,pc:G().min(1),pkf:gf,tsl:vf.optional()})),Af=q({name:G().min(1),relayBaseUrl:hf.optional(),directBaseUrls:$n(mf).default([]),transportSecurityLevel:_f.default(`e2ee-relay`),gatewayIdentity:Rl.optional(),gatewayAccessToken:G().min(1).optional(),connectedAt:G().datetime().optional()}),jf=q({gatewayId:G().min(1),deviceId:G().min(1),connectedAt:G().datetime().optional()}),Mf=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Sf,deviceId:G().min(1),deviceIdentity:Vl,clientNonce:qa}),Nf=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Sf,gatewayId:G().min(1),deviceId:G().min(1),clientNonce:qa,gatewayNonce:qa,gatewayPublicKeyFingerprint:G().min(1),gatewayEphemeralPublicKey:qa,signatureAlgorithm:J(`ed25519`),signature:qa}),Pf=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1),deviceIdentityFingerprint:G().min(1),clientEphemeralPublicKey:qa,signatureAlgorithm:J(`ed25519`),signature:qa}),Ff=q({version:J(1),securityLevel:J(`e2ee-relay`),cipherSuite:Sf,gatewayId:G().min(1),deviceId:G().min(1),keyEpoch:Cf,deviceIdentityFingerprint:G().min(1),deviceIdentityStatus:Bl}),If=Y([`gateway_restarted`,`gateway_available`]),Lf=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1),reason:If,retryable:J(!0)}),Rf=q({ticket:G().min(1),method:Y([`GET`,`HEAD`]),rangeHeader:G().min(1).optional(),responseMode:Y([`inline_base64`,`stream_upload`]).optional(),uploadUrl:G().url().optional(),uploadToken:G().min(1).optional()}).superRefine((e,t)=>{e.responseMode===`stream_upload`&&(e.uploadUrl||t.addIssue({code:U.custom,path:[`uploadUrl`],message:`uploadUrl is required when responseMode is stream_upload`}),e.uploadToken||t.addIssue({code:U.custom,path:[`uploadToken`],message:`uploadToken is required when responseMode is stream_upload`}))}),zf=q({status:er([J(200),J(206),J(416)]),headers:q({contentType:G().min(1),contentDisposition:G().min(1),contentLength:K().int().nonnegative(),etag:G().min(1),acceptRanges:J(`bytes`).optional(),contentRange:G().min(1).optional(),lastModified:G().min(1).optional(),cacheControl:G().min(1)}),bodyTransport:Y([`inline_base64`,`stream_upload`]).optional(),bodyBase64:qa.optional()}),Bf=q({}),Vf=zf,Hf=q({version:J(1),gatewayId:G().min(1),deviceId:G().min(1).optional(),code:Tf,message:G().min(1),retryable:Zn().optional()}),Uf=ef,Wf=tf,Gf=q({code:Y([`BAD_REQUEST`,`NOT_FOUND`,`UNAUTHORIZED`,`TIMEOUT`,`INTERNAL`,`GATEWAY_OFFLINE`,`TOKEN_INVALID`,`TOKEN_EXPIRED`,`GATEWAY_MISMATCH`,`GATEWAY_REVOKED`]),message:G().min(1),status:K().int().min(400).max(599),details:Qn().optional()}),Kf=Gf.extend({method:Qd.optional()}),qf=Gl.extend({gatewayId:G().min(1)}),Jf=ql.extend({relayToken:G().min(1).optional()}),Yf=Jl.extend({gatewayId:G().min(1),deviceId:G().min(1).optional()}),Xf=Yl.extend({gatewayId:G().min(1),relayToken:G().min(1).optional()}),Zf=q({gatewayId:G().min(1),gatewayIdentity:Rl,requestedAt:G().datetime()});q({grantType:J(`guest`),payload:Zf,signatureAlgorithm:J(`ed25519`),signature:qa});var Qf=q({grantType:Ef,token:G().min(1),expiresInSeconds:K().int().positive()}),$f=Y([`rpc`,`command`,`event`,`system`]),ep=nf,tp=rf,np=q({version:J(1),keyEpoch:Cf,counter:wf,iv:qa,ciphertext:qa,authTag:qa,plaintextEncoding:tp.default(ep),compression:af.default(`identity`),uncompressedByteLength:K().int().positive().optional(),compressedByteLength:K().int().positive().optional()});Y([`from_mobile`,`to_mobile`,`rpc.request`,`rpc.response`,`rpc.error`]);function rp(e){return{payload:e.optional(),encryptedPayload:np.optional()}}function ip(e){return{payload:e.optional(),compressedPayload:of.optional(),encryptedPayload:np.optional()}}var ap=q({gatewayId:G().min(1),mobileId:G().min(1).optional(),messageType:$f,requestId:G().min(1).optional()}),op=Y([`fresh_connect`,`gateway_replay`]),sp=q({deviceId:G().min(1),deliveryMode:op,gatewayAvailableAtConnect:Zn()}),cp=q({deviceId:G().min(1)}),lp=er([Ll,jd,q({type:J(`command.ack`),commandType:G().min(1),commandId:G().min(1).optional(),payload:Qn().optional()}),q({type:J(`command.error`),commandType:G().min(1).optional(),commandId:G().min(1).optional(),message:G().min(1)}),q({type:J(`relay.error`),error:Gf})]),up=tr(`type`,[ap.extend({type:J(`gateway.hello`),messageType:J(`system`),payload:Af}),ap.extend({type:J(`mobile.hello`),messageType:J(`system`),payload:jf}),ap.extend({type:J(`secure.client_hello`),messageType:J(`system`),payload:Mf}),ap.extend({type:J(`secure.gateway_hello`),mobileId:G().min(1),messageType:J(`system`),payload:Nf}),ap.extend({type:J(`secure.client_auth`),messageType:J(`system`),payload:Pf}),ap.extend({type:J(`secure.ready`),mobileId:G().min(1),messageType:J(`system`),payload:Ff}),ap.extend({type:J(`secure.handshake_required`),mobileId:G().min(1),messageType:J(`system`),payload:Lf}),ap.extend({type:J(`secure.error`),mobileId:G().min(1),messageType:J(`system`),payload:Hf}),ap.extend({type:J(`mobile.connected`),messageType:J(`system`),payload:sp}),ap.extend({type:J(`mobile.disconnected`),messageType:J(`system`),payload:cp}),ap.extend({type:J(`from_mobile`),messageType:J(`command`),mobileId:G().min(1),...rp(il)}),ap.extend({type:J(`to_mobile`),messageType:J(`event`),mobileId:G().min(1),...ip(lp)}),ap.extend({type:J(`rpc.request`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),...rp(Uf)}),ap.extend({type:J(`rpc.response`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),...ip(Wf)}),ap.extend({type:J(`rpc.error`),messageType:J(`rpc`),requestId:G().min(1),mobileId:G().min(1),...ip(Kf)}),ap.extend({type:J(`broadcast`),messageType:J(`event`),payload:Ll}),ap.extend({type:J(`pairing.claim.forward`),messageType:J(`system`),requestId:G().min(1),payload:qf}),ap.extend({type:J(`pairing.claim.result`),messageType:J(`system`),requestId:G().min(1),payload:Jf}),ap.extend({type:J(`auth.refresh.forward`),messageType:J(`system`),requestId:G().min(1),payload:Yf}),ap.extend({type:J(`auth.refresh.result`),messageType:J(`system`),requestId:G().min(1),payload:Xf}),ap.extend({type:J(`file.content.forward`),messageType:J(`system`),requestId:G().min(1),payload:Rf}),ap.extend({type:J(`file.content.result`),messageType:J(`system`),requestId:G().min(1),payload:zf}),ap.extend({type:J(`file.content.upload.started`),messageType:J(`system`),requestId:G().min(1),payload:Bf}),ap.extend({type:J(`relay.error`),messageType:J(`system`),payload:Gf})]);function dp(e){return JSON.stringify([`relay-gateway-guest-token-v1`,e.gatewayId,e.gatewayIdentity.algorithm,e.gatewayIdentity.publicKey,e.gatewayIdentity.publicKeyFingerprint,e.gatewayIdentity.keyVersion,e.gatewayIdentity.createdAt,e.requestedAt])}function fp(e){return JSON.stringify([e.gatewayId,e.clientHello.version,e.clientHello.securityLevel,e.clientHello.cipherSuite,e.clientHello.deviceId,e.clientHello.deviceIdentity.publicKey,e.clientHello.deviceIdentity.publicKeyFingerprint,e.clientHello.clientNonce,e.gatewayHello.gatewayNonce,e.gatewayHello.gatewayPublicKeyFingerprint,e.gatewayHello.gatewayEphemeralPublicKey])}function pp(e){return JSON.stringify([`relay-secure-gateway-hello-v1`,fp(e)])}function mp(e){return JSON.stringify([`relay-secure-client-auth-v1`,fp(e),e.clientAuth.clientEphemeralPublicKey])}function hp(e){let t=Cf.parse(e.keyEpoch??1);return JSON.stringify([`relay-secure-session-v1`,e.gatewayId,e.clientHello.version,e.clientHello.securityLevel,e.clientHello.cipherSuite,e.clientHello.deviceId,e.clientHello.deviceIdentity.publicKey,e.clientHello.deviceIdentity.publicKeyFingerprint,e.clientHello.clientNonce,e.gatewayHello.gatewayNonce,e.gatewayHello.gatewayPublicKeyFingerprint,e.gatewayHello.gatewayEphemeralPublicKey,e.clientAuth.clientEphemeralPublicKey,t])}function gp(e){let t=e.clientHello.cipherSuite;if(t!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${t}`);let n=Cf.parse(e.keyEpoch??1),r=Op(jp(hp({gatewayId:e.gatewayId,clientHello:e.clientHello,gatewayHello:e.gatewayHello,clientAuth:e.clientAuth,keyEpoch:n}))),i=Op(Ap(jp(`relay-secure-hkdf-salt-v1`),r)),a=jp(JSON.stringify([`relay-secure-key-schedule-v1`,e.gatewayId,e.clientHello.deviceId,t,n])),o=Dp(e.sharedSecret,i,a,72);return{keyEpoch:n,cipherSuite:t,transcriptHash:r,clientToGatewayKey:o.slice(0,32),gatewayToClientKey:o.slice(32,64),clientToGatewayNoncePrefix:o.slice(64,68),gatewayToClientNoncePrefix:o.slice(68,72)}}function _p(e){return e.role===`client`?{role:`client`,keyEpoch:e.keySchedule.keyEpoch,cipherSuite:e.keySchedule.cipherSuite,transcriptHash:e.keySchedule.transcriptHash,outboundKey:e.keySchedule.clientToGatewayKey,inboundKey:e.keySchedule.gatewayToClientKey,outboundNoncePrefix:e.keySchedule.clientToGatewayNoncePrefix,inboundNoncePrefix:e.keySchedule.gatewayToClientNoncePrefix,outboundCounter:0,highestInboundCounter:null}:{role:`gateway`,keyEpoch:e.keySchedule.keyEpoch,cipherSuite:e.keySchedule.cipherSuite,transcriptHash:e.keySchedule.transcriptHash,outboundKey:e.keySchedule.gatewayToClientKey,inboundKey:e.keySchedule.clientToGatewayKey,outboundNoncePrefix:e.keySchedule.gatewayToClientNoncePrefix,inboundNoncePrefix:e.keySchedule.clientToGatewayNoncePrefix,outboundCounter:0,highestInboundCounter:null}}function vp(e,t){let n=wf.parse(t);if(e.length!==4)throw Error(`nonce prefix must be 4 bytes`);let r=new Uint8Array(12);return r.set(e,0),r.set(Np(n),4),r}function yp(e,t){let n=wf.parse(t);if(e===null)return;let r=wf.parse(e);if(n<=r)throw Error(`counter_replay`);if(n-r>1e3)throw Error(`counter_gap_too_large`)}function bp(e){return JSON.stringify([`relay-secure-business-payload-v1`,e.metadata.frameType,e.metadata.messageType,e.metadata.gatewayId,e.metadata.requestId??``,e.encryptedPayload.version,e.encryptedPayload.keyEpoch,e.encryptedPayload.counter])}function xp(e){kp(e.session.cipherSuite);let t=e.session.outboundCounter,n=vp(e.session.outboundNoncePrefix,t),r=e.preparedPayload.payloadBytes,i=jp(bp({metadata:e.metadata,encryptedPayload:{version:1,keyEpoch:e.session.keyEpoch,counter:t}})),a=qi(e.session.outboundKey,n,i).encrypt(r),o=a.subarray(0,a.length-16),s=a.subarray(a.length-16);return e.session.outboundCounter=t+1,np.parse({version:1,keyEpoch:e.session.keyEpoch,counter:t,iv:Cp(n),ciphertext:Cp(o),authTag:Cp(s),plaintextEncoding:ep,compression:e.preparedPayload.compression,...e.preparedPayload.compression===`gzip`?{uncompressedByteLength:e.preparedPayload.uncompressedByteLength,compressedByteLength:e.preparedPayload.compressedByteLength}:{}})}function Sp(e){kp(e.session.cipherSuite);let t=np.parse(e.encryptedPayload);if(t.keyEpoch!==e.session.keyEpoch)throw Error(`key_epoch_mismatch`);yp(e.session.highestInboundCounter,t.counter);let n=vp(e.session.inboundNoncePrefix,t.counter),r=wp(t.iv);if(!Mp(r,n))throw Error(`decrypt_failed`);let i=jp(bp({metadata:e.metadata,encryptedPayload:t})),a=Ap(wp(t.ciphertext),wp(t.authTag)),o;try{o=qi(e.session.inboundKey,r,i).decrypt(a)}catch{throw Error(`decrypt_failed`)}e.session.highestInboundCounter=t.counter;try{return lf({payloadBytes:o,compression:t.compression,expectedUncompressedByteLength:t.uncompressedByteLength,parse:e.parse})}catch{throw Error(`decrypt_failed`)}}function Cp(e){let t=globalThis.Buffer;if(t)return t.from(e).toString(`base64`);let n=``;for(let t of e)n+=String.fromCharCode(t);if(typeof btoa!=`function`)throw Error(`base64 encoder unavailable`);return btoa(n)}function wp(e){let t=globalThis.Buffer;if(t)return new Uint8Array(t.from(e,`base64`));if(typeof atob!=`function`)throw Error(`base64 decoder unavailable`);let n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r}function Tp(e){return Cp(e).replace(/\+/gu,`-`).replace(/\//gu,`_`).replace(/=+$/u,``)}function Ep(e){return wp(e.replace(/-/gu,`+`).replace(/_/gu,`/`).padEnd(Math.ceil(e.length/4)*4,`=`))}function Dp(e,t,n,r){return r<=0?new Uint8Array:new Uint8Array(ya(Na,e,t.length>0?t:new Uint8Array(32),n,r))}function Op(e){return new Uint8Array(Na(e))}function kp(e){if(e!==`ed25519-x25519-hkdf-sha256-aes-256-gcm-v1`)throw Error(`unsupported cipher suite: ${e}`)}function Ap(...e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function jp(e){return new TextEncoder().encode(e)}function Mp(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Np(e){if(!Number.isSafeInteger(e))throw Error(`counter must be a safe integer`);let t=Math.floor(e/4294967296),n=e>>>0,r=new Uint8Array(8),i=new DataView(r.buffer);return i.setUint32(0,t),i.setUint32(4,n),r}function Pp(e){return Tp(Na(wp(e)).subarray(0,16))}function Fp(e){if(e.type!==`native.raw`)return null;let t=Vp(e.payload.raw),n=Vp(t.message),r=Vp(n.params),i=Vp(r.msg),a=Hp(n.method)??Hp(t.method);if(!a)return null;let o=Hp(i.type)??``;if(!zp(a)&&!Bp(o))return null;let s=Rp(t);if(!s||!s.delta)return null;let c=Hp(r.conversationId)??Hp(r.conversation_id)??``,l=Hp(i.thread_id)??Hp(i.threadId)??Hp(r.threadId)??Hp(r.thread_id)??``,u=Hp(i.turn_id)??Hp(i.turnId)??Hp(r.turnId)??Hp(r.turn_id)??``,d=Hp(i.item_id)??Hp(i.itemId)??Hp(r.itemId)??Hp(r.item_id)??``,f=Hp(t.source)??``,p=Up(i.summaryIndex??i.summary_index??r.summaryIndex??r.summary_index),m=Up(i.contentIndex??i.content_index??r.contentIndex??r.content_index);return{key:[e.sessionId,f,a,c,l,u,d,o,p,m].join(`|`),delta:s.delta,method:a}}function Ip(e,t){let n=Fp(e),r=Fp(t);if(!n||!r||n.key!==r.key)return null;let i=`${n.delta}${r.delta}`,a=Vp(t.payload.raw),o=Rp(a)?.location??Rp(Vp(e.payload.raw))?.location;return o?{...t,eventId:e.eventId,ts:t.ts,payload:{...t.payload,raw:Lp(a,o,i)}}:null}function Lp(e,t,n){if(t===`raw.delta`)return{...e,delta:n};let r=Vp(e.message),i=Vp(r.params);if(t===`params.delta`)return{...e,message:{...r,params:{...i,delta:n}}};let a=Vp(i.msg);return{...e,message:{...r,params:{...i,msg:{...a,delta:n}}}}}function Rp(e){let t=Vp(Vp(e.message).params),n=Vp(t.msg);return typeof n.delta==`string`?{delta:n.delta,location:`msg.delta`}:typeof t.delta==`string`?{delta:t.delta,location:`params.delta`}:typeof e.delta==`string`?{delta:e.delta,location:`raw.delta`}:null}function zp(e){return e.includes(`_delta`)||e.endsWith(`/delta`)||e.endsWith(`Delta`)||e.includes(`/delta/`)}function Bp(e){return e.endsWith(`_delta`)||e.endsWith(`Delta`)}function Vp(e){return typeof e==`object`&&e?e:{}}function Hp(e){return typeof e==`string`&&e.trim()||void 0}function Up(e){return typeof e==`number`&&Number.isFinite(e)?String(e):typeof e==`bigint`?e.toString():Hp(e)??``}var Wp=new Set([`claude.history.getSessionMessages`,`claude.history.jsonl`]),Gp=/\u001B\[[0-?]*[ -/]*[@-~]/g,Kp={"thread.started":0,"thread.title.updated":1,"turn.started":2,"item.started":3,"item.updated":4,"item.completed":5,"turn.completed":6,"turn.failed":6,"tool.permission.requested":7,"user.input.requested":7};function qp(e,t){let n=[],r=0,i=[...t].filter(t=>t.sessionId===e).sort((e,t)=>e.ts.localeCompare(t.ts)),a=[],o=()=>(r+=1,`raw_proj_item_${e}_${r}`);for(let e of i){let t=Ml.safeParse(e.type);if(t.success){n.push(Qp(e,t.data,sm(e.payload.raw),e.eventId));continue}if(e.type!==`native.raw`)continue;let r=sm(e.payload.raw),i=Yp(e,r);if(i.length>0&&n.push(...i),r.historyReplay!==!0)continue;let o=X(r.source);if(o?.startsWith(`codex.history.thread_read`)){n.push(...Xp(e,r));continue}o&&Wp.has(o)&&a.push(e)}a.length>0&&n.push(...Zp(a,o));let s=new Map,c=new Map;for(let e of n){let t=nm(e);if(!t){s.set(e.eventId,e);continue}let n=rm(e.payload.raw),r=c.get(t);(!r||n>r.richness)&&c.set(t,{event:e,richness:n})}for(let{event:e}of c.values())s.set(e.eventId,e);return[...s.values()].sort((e,t)=>{let n=e.ts.localeCompare(t.ts);if(n!==0)return n;let r=Om(e.type)-Om(t.type);return r===0?e.eventId.localeCompare(t.eventId):r})}function Jp(e,t,n){return fu(e,qp(e,t),n)}function Yp(e,t){if(e.type!==`native.raw`||X(t.source)!==`codex.app_server`)return[];let n=sm(t.message),r=sm(n.params),i=X(n.method)??X(t.method);if(!i)return[];if(i===`turn/started`||i===`turn/completed`||i===`turn/failed`||i===`turn/interrupted`){let t=em(sm(r.turn),r);if(Object.keys(t).length===0)return[];let n=i===`turn/started`?`turn.started`:i===`turn/failed`?`turn.failed`:`turn.completed`,a=X(t.status)??(i===`turn/completed`?`completed`:i===`turn/interrupted`?`interrupted`:`failed`),o=sm(t.error);return[Qp(e,n,{turn:t,status:a,turn_id:X(t.id),source_event_type:`codex.app_server`,...n===`turn.failed`?{error:o}:{}},`${e.eventId}:${n.replace(`.`,`_`)}`)]}if(i===`item/started`||i===`item/completed`){let t=$p(sm(r.item));if(Object.keys(t).length===0)return[];let n=X(r.turn_id)??X(r.turnId)??X(sm(r.turn).id)??X(t.turn_id)??X(t.turnId);return[Qp(e,i===`item/started`?`item.started`:`item.completed`,{turn_id:n,item:t,source_event_type:`codex.app_server`},`${e.eventId}:${i===`item/started`?`item_started`:`item_completed`}`)]}return[]}function Xp(e,t){let n=[],r=sm(t.message),i=X(r.scope);if(i===`thread`){let t=sm(r.thread),i=X(t.id);n.push(Qp(e,`thread.started`,{thread_id:i,thread:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:thread_started`));let a=lm(X(t.preview));return a&&n.push(Qp(e,`thread.title.updated`,{title:a,source:`codex.history.thread_read`,thread_id:i},`${e.eventId}:thread_title_updated`)),n}if(i===`turn`){let t=sm(r.turn),i=X(t.status);return n.push(Qp(e,`turn.started`,{turn:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_started`)),i===`completed`||i===`interrupted`?n.push(Qp(e,`turn.completed`,{status:i,turn:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_completed`)):i===`failed`&&n.push(Qp(e,`turn.failed`,{status:i,turn:t,error:sm(t.error),source_event_type:`codex.history.thread_read`},`${e.eventId}:turn_failed`)),n}if(i===`item`){let t=$p(sm(r.item)),i=X(r.turn_id)??X(r.turnId)??X(t.turn_id);n.push(Qp(e,`item.completed`,{turn_id:i,item:t,source_event_type:`codex.history.thread_read`},`${e.eventId}:item_completed`))}return n}function Zp(e,t){let n=[],r=e[0];if(!r)return n;let i=sm(r.payload.raw),a=sm(i.message),o=X(i.native_session_id)??X(a.session_id)??r.sessionId,s=new Map,c=!1,l=0,u;n.push(Qp(r,`thread.started`,{thread_id:o,source:`claude.history.getSessionMessages`},`${r.eventId}:thread_started`));let d=(e,t,r)=>u||(l+=1,u={id:`claude_hist_turn_${l}`,terminal:!1},n.push(Qp(e,`turn.started`,{turn_id:u.id,source_event_type:t,source_line:r},`${e.eventId}:turn_started:${u.id}`)),u),f=(e,t,r)=>{if(!u||u.terminal){u=void 0;return}u.terminal=!0,n.push(Qp(e,`turn.completed`,{turn_id:u.id,source_event_type:t,source_line:r},`${e.eventId}:turn_completed:${u.id}`)),u=void 0},p=(e,t,r,i)=>{let a=d(e,t,r);a.terminal||(a.terminal=!0,n.push(Qp(e,`turn.failed`,{turn_id:a.id,source_event_type:t,source_line:r,error:{message:i}},`${e.eventId}:turn_failed:${a.id}`)),u=void 0)};for(let r of e){let e=sm(r.payload.raw),i=sm(e.message),a=X(e.native_type)??X(i.type),l=sm(i.message),u=X(e.source)??`claude.history.getSessionMessages`,m=Dm(e.source_line);if(a===`user`){let e=um(l),a=dm(l),p=pm(l);if(e||a.length>0){if(e&&!c){let t=lm(e);t&&(n.push(Qp(r,`thread.title.updated`,{title:t,source:`claude.history.first_user_message`,thread_id:o},`${r.eventId}:thread_title_updated`)),c=!0)}f(r,u,m);let s=d(r,u,m);n.push(Qp(r,`item.completed`,{item:{id:X(i.uuid)??t(),type:`user_message`,...e?{text:e}:{},...a.length>0?{attachments:a}:{},turn_id:s.id,source_event_type:u},source_line:m},`${r.eventId}:item_completed_user`))}p.forEach((e,i)=>{let a=e.toolUseId?s.get(e.toolUseId):void 0;if(e.toolUseId&&s.delete(e.toolUseId),a?.skipReplay)return;let o=d(r,u,m);n.push(Qp(r,`item.completed`,{item:gm(a,e,o.id,t),source_line:m},`${r.eventId}:item_completed_tool_result_${i+1}`))});continue}if(a!==`assistant`)continue;let h=d(r,u,m);fm(l).forEach((e,i)=>{e.id&&s.set(e.id,e),!e.skipReplay&&n.push(Qp(r,`item.started`,{item:{id:e.id??t(),type:`tool_status`,status:`running`,tool_name:e.name,title:e.title,text:e.title,status_label:e.pendingStatusLabel,display_as:`tool_card`,response_label:e.responseLabel,prompt:e.prompt,file_path:e.filePath,turn_id:h.id,source_event_type:u},source_line:m},`${r.eventId}:item_started_tool_use_${i+1}`))});let g=um(l);g&&n.push(Qp(r,`item.completed`,{item:{id:X(l.id)??X(i.uuid)??t(),type:`agent_message`,text:g,turn_id:h.id,source_event_type:u},source_line:m},`${r.eventId}:item_completed_assistant`));let _=Em(X(i.error));_&&p(r,u,m,_)}let m=e[e.length-1];if(m){let e=sm(m.payload.raw);f(m,X(e.source)??`claude.history.getSessionMessages`,Dm(e.source_line))}return n}function Qp(e,t,n,r){return{v:e.v,provider:e.provider,sessionId:e.sessionId,projectId:e.projectId,eventId:r,ts:e.ts,type:t,payload:{raw:n}}}function $p(e){let t=im(e),n=X(e.type);return n&&(t.type=tm(n)),t}function em(e,t){let n=im(e),r=X(e.id)??X(t.turn_id)??X(t.turnId);return r&&(n.id=r),n}function tm(e){switch(e){case`userMessage`:return`user_message`;case`agentMessage`:return`agent_message`;case`commandExecution`:return`command_execution`;case`fileChange`:return`file_change`;case`webSearch`:return`web_search`;case`mcpToolCall`:return`mcp_tool_call`;case`todoList`:return`todo_list`;case`contextCompaction`:return`context_compaction`;default:return om(e)}}function nm(e){if(e.type!==`item.started`&&e.type!==`item.completed`)return;let t=sm(e.payload.raw),n=sm(t.item),r=X(n.id)??X(n.item_id)??X(n.itemId);if(!r)return;let i=X(t.turn_id)??X(t.turnId)??X(n.turn_id)??X(n.turnId)??``;return[e.type,e.sessionId,i,r].join(`|`)}function rm(e){return Array.isArray(e)?e.reduce((e,t)=>e+rm(t),0):e&&typeof e==`object`?Object.entries(e).reduce((e,[t,n])=>e+t.length+rm(n),1):typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?1:0}function im(e){let t={};for(let[n,r]of Object.entries(e))t[om(n)]=am(r);return t}function am(e){return Array.isArray(e)?e.map(e=>am(e)):typeof e==`object`&&e?im(e):e}function om(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1_$2`).toLowerCase()}function sm(e){return typeof e==`object`&&e?e:{}}function X(e){return typeof e==`string`&&e.trim()||void 0}function cm(e,t){for(let n of t){let t=e[n];if(typeof t==`string`&&t.length>0)return t}}function lm(e,t=60){if(!e)return;let n=e.replace(/\s+/g,` `).trim();if(!n)return;let r=Array.from(n);return r.length<=t?n:r.slice(0,t).join(``).trimEnd()}function um(e){let t=X(e.content);if(t)return Em(t);let n=X(e.text)??X(e.prompt);if(n)return Em(n);let r=Array.isArray(e.content)?e.content:[],i=[];for(let e of r){if(typeof e==`string`&&e.trim()){i.push(e);continue}let t=sm(e),n=X(t.type);if(n&&n!==`text`)continue;let r=X(t.text)??X(t.content)??Tm(t);r&&i.push(r)}if(i.length!==0)return Em(i.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "craby-gateway",
3
- "version": "0.30.6",
3
+ "version": "0.30.7",
4
4
  "description": "Craby desktop gateway CLI",
5
5
  "bin": {
6
6
  "craby-gateway": "dist-sea/gateway.cjs"