@codexhost/cli-darwin-x64 0.25.1 → 0.26.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/app/codexhost-distribution.json +1 -1
- package/app/console-server.mjs +174 -18
- package/app/console-web.js +543 -230
- package/app/desktop-controller.mjs +154 -5
- package/app/host-runtime.mjs +1064 -645
- package/app/plugins/antigravity/plugin.mjs +202 -19
- package/app/plugins/claude-code/plugin.mjs +195 -10
- package/app/plugins/codebuddy/plugin.mjs +154 -5
- package/app/plugins/codex-usage/plugin.mjs +154 -5
- package/app/plugins/copilot/plugin.mjs +154 -5
- package/app/plugins/cursor-cli/plugin.mjs +154 -5
- package/app/plugins/deepseek-harness/plugin.mjs +182 -36
- package/app/plugins/devin/plugin.mjs +154 -5
- package/app/plugins/grok/plugin.mjs +154 -5
- package/app/plugins/hermes/plugin.mjs +198 -20
- package/app/plugins/kimi-code/plugin.mjs +154 -5
- package/app/plugins/kiro-cli/plugin.mjs +154 -5
- package/app/plugins/omp/plugin.mjs +154 -5
- package/app/plugins/opencode/plugin.mjs +155 -9
- package/app/plugins/pi/plugin.mjs +296 -33
- package/app/plugins/qoder/plugin.mjs +154 -5
- package/app/plugins/qoder-cn/plugin.mjs +154 -5
- package/app/plugins/qwen-code/plugin.mjs +154 -5
- package/app/plugins/workbuddy/plugin.mjs +154 -5
- package/app/plugins/zcode/plugin.mjs +154 -5
- package/app/renderer-extension.js +1132 -330
- package/app/web/assets/{index-DUOvhHbV.js → index-Bl_9AU27.js} +70 -70
- package/app/web/assets/{index-CTCFIQbU.css → index-arwoPpaG.css} +1 -1
- package/app/web/codexhost-settings.js +230 -140
- package/app/web/index.html +2 -2
- package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -10
- package/app/web/plugins/deepseek-ai__dsh-client-ui-brand-official/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +13 -13
- package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +73 -73
- package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +75 -75
- package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
- package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +11 -11
- package/app/web-modules/server.mjs +14416 -13144
- package/bin/codexhost +0 -0
- package/libexec/CodexHost.app/Contents/Info.plist +2 -2
- package/libexec/CodexHost.app/Contents/MacOS/CodexHost +0 -0
- package/libexec/codexhost-shim +0 -0
- package/libexec/codexhost-updater +0 -0
- package/package.json +1 -1
|
@@ -119,22 +119,20 @@ function Hi(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...v(n)})}//
|
|
|
119
119
|
function Ui(e,t){let n=/* @__PURE__ */ Wi(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(it(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(it(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
|
|
120
120
|
function Wi(e,t){let n=new b({check:`custom`,...v(t)});return n._zod.check=e,n}function Gi(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Br,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function C(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,C(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&w(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Ki(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
121
121
|
|
|
122
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}}function qi(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Yi(t,`input`,e.processors),output:Yi(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function w(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return w(r.element,n);if(r.type===`set`)return w(r.valueType,n);if(r.type===`lazy`)return w(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return w(r.innerType,n);if(r.type===`intersection`)return w(r.left,n)||w(r.right,n);if(r.type===`record`||r.type===`map`)return w(r.keyType,n)||w(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:w(r.in,n)||w(r.out,n);if(r.type===`object`){for(let e in r.shape)if(w(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(w(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(w(e,n))return!0;return!!(r.rest&&w(r.rest,n))}return!1}let Ji=(e,t={})=>n=>{let r=Gi({...n,processors:t});return C(e,r),Ki(r,e),qi(r,e)},Yi=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Gi({...i??{},target:a,io:t,processors:n});return C(e,o),Ki(o,e),qi(o,e)},Xi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Zi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Xi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Qi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},$i=(e,t,n,r)=>{n.type=`boolean`},ea=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ta=(e,t,n,r)=>{n.not={}},na=(e,t,n,r)=>{let i=e._zod.def,a=Te(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ra=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ia=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},aa=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},oa=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=C(a.element,t,{...r,path:[...r.path,`items`]})},sa=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=C(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=C(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ca=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>C(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},la=(e,t,n,r)=>{let i=e._zod.def,a=C(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=C(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ua=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>C(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?C(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},da=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=C(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=C(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=C(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},fa=(e,t,n,r)=>{let i=e._zod.def,a=C(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},pa=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ma=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},ha=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},ga=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},_a=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;C(o,t,r);let s=t.seen.get(e);s.ref=o},va=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ya=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ba=(e,t,n,r)=>{let i=e._zod.innerType;C(i,t,r);let a=t.seen.get(e);a.ref=i},xa=/*@__PURE__*/ h(`ZodISODateTime`,(e,t)=>{Mn.init(e,t),O.init(e,t)});function Sa(e){return/* @__PURE__ */ ui(xa,e)}let Ca=/*@__PURE__*/ h(`ZodISODate`,(e,t)=>{Nn.init(e,t),O.init(e,t)});function wa(e){return/* @__PURE__ */ di(Ca,e)}let Ta=/*@__PURE__*/ h(`ZodISOTime`,(e,t)=>{Pn.init(e,t),O.init(e,t)});function Ea(e){return/* @__PURE__ */ fi(Ta,e)}let Da=/*@__PURE__*/ h(`ZodISODuration`,(e,t)=>{Fn.init(e,t),O.init(e,t)});function Oa(e){return/* @__PURE__ */ pi(Da,e)}let T=/*@__PURE__*/ h(`ZodError`,(e,t)=>{ot.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>lt(e,t)},flatten:{value:t=>ct(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ee,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ee,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ka=/* @__PURE__ */ ut(T),Aa=/* @__PURE__ */ dt(T),ja=/* @__PURE__ */ ft(T),Ma=/* @__PURE__ */ mt(T),Na=/* @__PURE__ */ gt(T),Pa=/* @__PURE__ */ _t(T),Fa=/* @__PURE__ */ vt(T),Ia=/* @__PURE__ */ yt(T),La=/* @__PURE__ */ bt(T),Ra=/* @__PURE__ */ xt(T),za=/* @__PURE__ */ St(T),Ba=/* @__PURE__ */ Ct(T),Va=/* @__PURE__ */ new WeakMap;function Ha(e,t,n){let r=Object.getPrototypeOf(e),i=Va.get(r);if(i||(i=/* @__PURE__ */ new Set,Va.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let E=/*@__PURE__*/ h(`ZodType`,(e,t)=>(x.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Yi(e,`input`),output:Yi(e,`output`)}}),e.toJSONSchema=Ji(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>ka(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ja(e,t,n),e.parseAsync=async(t,n)=>Aa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ma(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Na(e,t,n),e.decode=(t,n)=>Pa(e,t,n),e.encodeAsync=async(t,n)=>Fa(e,t,n),e.decodeAsync=async(t,n)=>Ia(e,t,n),e.safeEncode=(t,n)=>La(e,t,n),e.safeDecode=(t,n)=>Ra(e,t,n),e.safeEncodeAsync=async(t,n)=>za(e,t,n),e.safeDecodeAsync=async(t,n)=>Ba(e,t,n),Ha(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Ne(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ue(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rs(e,t))},superRefine(e,t){return this.check(is(e,t))},overwrite(e){return this.check(/* @__PURE__ */ Pi(e))},optional(){return Io(this)},exactOptional(){return Ro(this)},nullable(){return Bo(this)},nullish(){return Io(Bo(this))},nonoptional(e){return Ko(this,e)},array(){return M(this)},or(e){return F([this,e])},and(e){return Do(this,e)},transform(e){return Xo(this,Po(e))},default(e){return Ho(this,e)},prefault(e){return Wo(this,e)},catch(e){return Jo(this,e)},pipe(e){return Xo(this,e)},readonly(){return Qo(this)},describe(e){let t=this.clone();return Br.add(t,{description:e}),t},meta(...e){if(e.length===0)return Br.get(this);let t=this.clone();return Br.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Br.get(e)?.description},configurable:!0}),e)),Ua=/*@__PURE__*/ h(`_ZodString`,(e,t)=>{bn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ha(e,`_ZodString`,{regex(...e){return this.check(/* @__PURE__ */ Oi(...e))},includes(...e){return this.check(/* @__PURE__ */ ji(...e))},startsWith(...e){return this.check(/* @__PURE__ */ Mi(...e))},endsWith(...e){return this.check(/* @__PURE__ */ Ni(...e))},min(...e){return this.check(/* @__PURE__ */ Ei(...e))},max(...e){return this.check(/* @__PURE__ */ Ti(...e))},length(...e){return this.check(/* @__PURE__ */ Di(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Ei(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ ki(e))},uppercase(e){return this.check(/* @__PURE__ */ Ai(e))},trim(){return this.check(/* @__PURE__ */ Ii())},normalize(...e){return this.check(/* @__PURE__ */ Fi(...e))},toLowerCase(){return this.check(/* @__PURE__ */ Li())},toUpperCase(){return this.check(/* @__PURE__ */ Ri())},slugify(){return this.check(/* @__PURE__ */ zi())}})}),Wa=/*@__PURE__*/ h(`ZodString`,(e,t)=>{bn.init(e,t),Ua.init(e,t),e.email=t=>e.check(/* @__PURE__ */ Hr(Ga,t)),e.url=t=>e.check(/* @__PURE__ */ Jr(Ya,t)),e.jwt=t=>e.check(/* @__PURE__ */ li(fo,t)),e.emoji=t=>e.check(/* @__PURE__ */ Yr(Za,t)),e.guid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.uuid=t=>e.check(/* @__PURE__ */ Wr(qa,t)),e.uuidv4=t=>e.check(/* @__PURE__ */ Gr(qa,t)),e.uuidv6=t=>e.check(/* @__PURE__ */ Kr(qa,t)),e.uuidv7=t=>e.check(/* @__PURE__ */ qr(qa,t)),e.nanoid=t=>e.check(/* @__PURE__ */ Xr(Qa,t)),e.guid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.cuid=t=>e.check(/* @__PURE__ */ Zr($a,t)),e.cuid2=t=>e.check(/* @__PURE__ */ Qr(eo,t)),e.ulid=t=>e.check(/* @__PURE__ */ $r(to,t)),e.base64=t=>e.check(/* @__PURE__ */ oi(co,t)),e.base64url=t=>e.check(/* @__PURE__ */ si(lo,t)),e.xid=t=>e.check(/* @__PURE__ */ ei(no,t)),e.ksuid=t=>e.check(/* @__PURE__ */ ti(ro,t)),e.ipv4=t=>e.check(/* @__PURE__ */ ni(io,t)),e.ipv6=t=>e.check(/* @__PURE__ */ ri(ao,t)),e.cidrv4=t=>e.check(/* @__PURE__ */ ii(oo,t)),e.cidrv6=t=>e.check(/* @__PURE__ */ ai(so,t)),e.e164=t=>e.check(/* @__PURE__ */ ci(uo,t)),e.datetime=t=>e.check(Sa(t)),e.date=t=>e.check(wa(t)),e.time=t=>e.check(Ea(t)),e.duration=t=>e.check(Oa(t))});function D(e){return/* @__PURE__ */ Vr(Wa,e)}let O=/*@__PURE__*/ h(`ZodStringFormat`,(e,t)=>{S.init(e,t),Ua.init(e,t)}),Ga=/*@__PURE__*/ h(`ZodEmail`,(e,t)=>{Cn.init(e,t),O.init(e,t)}),Ka=/*@__PURE__*/ h(`ZodGUID`,(e,t)=>{xn.init(e,t),O.init(e,t)}),qa=/*@__PURE__*/ h(`ZodUUID`,(e,t)=>{Sn.init(e,t),O.init(e,t)});function Ja(e){return/* @__PURE__ */ Wr(qa,e)}let Ya=/*@__PURE__*/ h(`ZodURL`,(e,t)=>{wn.init(e,t),O.init(e,t)});function Xa(e){return/* @__PURE__ */ Jr(Ya,e)}let Za=/*@__PURE__*/ h(`ZodEmoji`,(e,t)=>{Tn.init(e,t),O.init(e,t)}),Qa=/*@__PURE__*/ h(`ZodNanoID`,(e,t)=>{En.init(e,t),O.init(e,t)}),$a=/*@__PURE__*/ h(`ZodCUID`,(e,t)=>{Dn.init(e,t),O.init(e,t)}),eo=/*@__PURE__*/ h(`ZodCUID2`,(e,t)=>{On.init(e,t),O.init(e,t)}),to=/*@__PURE__*/ h(`ZodULID`,(e,t)=>{kn.init(e,t),O.init(e,t)}),no=/*@__PURE__*/ h(`ZodXID`,(e,t)=>{An.init(e,t),O.init(e,t)}),ro=/*@__PURE__*/ h(`ZodKSUID`,(e,t)=>{jn.init(e,t),O.init(e,t)}),io=/*@__PURE__*/ h(`ZodIPv4`,(e,t)=>{In.init(e,t),O.init(e,t)}),ao=/*@__PURE__*/ h(`ZodIPv6`,(e,t)=>{Ln.init(e,t),O.init(e,t)}),oo=/*@__PURE__*/ h(`ZodCIDRv4`,(e,t)=>{Rn.init(e,t),O.init(e,t)}),so=/*@__PURE__*/ h(`ZodCIDRv6`,(e,t)=>{zn.init(e,t),O.init(e,t)}),co=/*@__PURE__*/ h(`ZodBase64`,(e,t)=>{Vn.init(e,t),O.init(e,t)}),lo=/*@__PURE__*/ h(`ZodBase64URL`,(e,t)=>{Un.init(e,t),O.init(e,t)}),uo=/*@__PURE__*/ h(`ZodE164`,(e,t)=>{Wn.init(e,t),O.init(e,t)}),fo=/*@__PURE__*/ h(`ZodJWT`,(e,t)=>{Kn.init(e,t),O.init(e,t)}),po=/*@__PURE__*/ h(`ZodNumber`,(e,t)=>{qn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r),Ha(e,`ZodNumber`,{gt(e,t){return this.check(/* @__PURE__ */ Si(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},min(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},lt(e,t){return this.check(/* @__PURE__ */ bi(e,t))},lte(e,t){return this.check(/* @__PURE__ */ xi(e,t))},max(e,t){return this.check(/* @__PURE__ */ xi(e,t))},int(e){return this.check(A(e))},safe(e){return this.check(A(e))},positive(e){return this.check(/* @__PURE__ */ Si(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Ci(0,e))},negative(e){return this.check(/* @__PURE__ */ bi(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ xi(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ wi(e,t))},step(e,t){return this.check(/* @__PURE__ */ wi(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function k(e){return/* @__PURE__ */ mi(po,e)}let mo=/*@__PURE__*/ h(`ZodNumberFormat`,(e,t)=>{Jn.init(e,t),po.init(e,t)});function A(e){return/* @__PURE__ */ hi(mo,e)}let ho=/*@__PURE__*/ h(`ZodBoolean`,(e,t)=>{Yn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r)});function j(e){return/* @__PURE__ */ gi(ho,e)}let go=/*@__PURE__*/ h(`ZodNull`,(e,t)=>{Xn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(e,t,n,r)});function _o(e){return/* @__PURE__ */ _i(go,e)}let vo=/*@__PURE__*/ h(`ZodUnknown`,(e,t)=>{Zn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function yo(){return/* @__PURE__ */ vi(vo)}let bo=/*@__PURE__*/ h(`ZodNever`,(e,t)=>{Qn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r)});function xo(e){return/* @__PURE__ */ yi(bo,e)}let So=/*@__PURE__*/ h(`ZodArray`,(e,t)=>{er.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),e.element=t.element,Ha(e,`ZodArray`,{min(e,t){return this.check(/* @__PURE__ */ Ei(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Ei(1,e))},max(e,t){return this.check(/* @__PURE__ */ Ti(e,t))},length(e,t){return this.check(/* @__PURE__ */ Di(e,t))},unwrap(){return this.element}})});function M(e,t){return/* @__PURE__ */ Bi(So,e,t)}let Co=/*@__PURE__*/ h(`ZodObject`,(e,t)=>{ar.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sa(e,t,n,r),_(e,`shape`,()=>t.shape),Ha(e,`ZodObject`,{keyof(){return R(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:yo()})},loose(){return this.clone({...this._zod.def,catchall:yo()})},strict(){return this.clone({...this._zod.def,catchall:xo()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Je(this,e)},safeExtend(e){return Ye(this,e)},merge(e){return Xe(this,e)},pick(e){return Ke(this,e)},omit(e){return qe(this,e)},partial(...e){return Ze(Fo,this,e[0])},required(...e){return Qe(Go,this,e[0])}})});function N(e,t){let n={type:`object`,shape:e??{},...v(t)};return new Co(n)}function P(e,t){return new Co({type:`object`,shape:e,catchall:xo(),...v(t)})}let wo=/*@__PURE__*/ h(`ZodUnion`,(e,t)=>{sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ca(e,t,n,r),e.options=t.options});function F(e,t){return new wo({type:`union`,options:e,...v(t)})}let To=/*@__PURE__*/ h(`ZodDiscriminatedUnion`,(e,t)=>{wo.init(e,t),cr.init(e,t)});function I(e,t,n){return new To({type:`union`,options:t,discriminator:e,...v(n)})}let Eo=/*@__PURE__*/ h(`ZodIntersection`,(e,t)=>{lr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>la(e,t,n,r)});function Do(e,t){return new Eo({type:`intersection`,left:e,right:t})}let Oo=/*@__PURE__*/ h(`ZodTuple`,(e,t)=>{fr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ua(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function ko(e,t,n){let r=t instanceof x;return new Oo({type:`tuple`,items:e,rest:r?t:null,...v(r?n:t)})}let Ao=/*@__PURE__*/ h(`ZodRecord`,(e,t)=>{gr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>da(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function L(e,t,n){return!t||!t._zod?new Ao({type:`record`,keyType:D(),valueType:e,...v(t)}):new Ao({type:`record`,keyType:e,valueType:t,...v(n)})}let jo=/*@__PURE__*/ h(`ZodEnum`,(e,t)=>{_r.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>na(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})}});function R(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new jo({type:`enum`,entries:n,...v(t)})}let Mo=/*@__PURE__*/ h(`ZodLiteral`,(e,t)=>{vr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ra(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function z(e,t){return new Mo({type:`literal`,values:Array.isArray(e)?e:[e],...v(t)})}let No=/*@__PURE__*/ h(`ZodTransform`,(e,t)=>{yr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aa(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(it(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(it(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Po(e){return new No({type:`transform`,transform:e})}let Fo=/*@__PURE__*/ h(`ZodOptional`,(e,t)=>{xr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Fo({type:`optional`,innerType:e})}let Lo=/*@__PURE__*/ h(`ZodExactOptional`,(e,t)=>{Sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ro(e){return new Lo({type:`optional`,innerType:e})}let zo=/*@__PURE__*/ h(`ZodNullable`,(e,t)=>{Cr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bo(e){return new zo({type:`nullable`,innerType:e})}let Vo=/*@__PURE__*/ h(`ZodDefault`,(e,t)=>{wr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ma(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ho(e,t){return new Vo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Uo=/*@__PURE__*/ h(`ZodPrefault`,(e,t)=>{Er.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ha(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wo(e,t){return new Uo({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Go=/*@__PURE__*/ h(`ZodNonOptional`,(e,t)=>{Dr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ko(e,t){return new Go({type:`nonoptional`,innerType:e,...v(t)})}let qo=/*@__PURE__*/ h(`ZodCatch`,(e,t)=>{kr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ga(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jo(e,t){return new qo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let Yo=/*@__PURE__*/ h(`ZodPipe`,(e,t)=>{Ar.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.in=t.in,e.out=t.out});function Xo(e,t){return new Yo({type:`pipe`,in:e,out:t})}let Zo=/*@__PURE__*/ h(`ZodReadonly`,(e,t)=>{Mr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>va(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qo(e){return new Zo({type:`readonly`,innerType:e})}let $o=/*@__PURE__*/ h(`ZodLazy`,(e,t)=>{Pr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ba(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function es(e){return new $o({type:`lazy`,getter:e})}let ts=/*@__PURE__*/ h(`ZodCustom`,(e,t)=>{Fr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ia(e,t,n,r)});function ns(e,t){return/* @__PURE__ */ Vi(ts,e??(()=>!0),t)}function rs(e,t={}){return/* @__PURE__ */ Hi(ts,e,t)}function is(e,t){return/* @__PURE__ */ Ui(e,t)}function as(e){return(t,n)=>{for(let r of e)Object.hasOwn(t,r)&&t[r]===void 0&&n.addIssue({code:`custom`,path:[r],message:`Explicit undefined is not valid JSON`})}}let os=F([D(),k(),j(),_o()]);function ss(e){let t=/* @__PURE__ */ new WeakSet,n=[{value:e,leaving:!1}];try{for(;n.length>0;){let e=n.pop();if(!e)break;if(e.leaving)t.delete(e.value);else if(typeof e.value==`object`&&e.value!==null){if(t.has(e.value))return!1;t.add(e.value),n.push({value:e.value,leaving:!0});for(let t of Object.values(e.value))n.push({value:t,leaving:!1})}}}catch{return!1}return!0}let cs=ns(ss,{message:`JSON value must not contain circular references`}),ls=es(()=>F([os,M(ls),L(D(),ls)])),B=cs.pipe(ls);cs.pipe(M(ls));let us=cs.pipe(L(D(),ls)),ds=P({code:D().min(1),message:D().min(1),retryable:j(),diagnostic:D().min(1).optional(),stage:D().min(1).optional(),durationMs:k().int().nonnegative().optional(),stderrTail:D().min(1).optional()}).superRefine(as([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),fs=D().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),ps=e=>D().min(1).max(e).refine(e=>e.trim().length>0),ms=L(fs,N({label:ps(256).optional(),description:ps(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),hs=L(fs,ps(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),gs=D().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),V=gs.brand(),H=gs.brand(),_s=gs.brand();gs.brand(),gs.brand();let vs=D().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),U=vs.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),ys=N({modes:M(N({id:U,label:vs.max(256),description:vs.max(1024).optional(),dangerous:j().optional(),localizations:ms.optional()}).strict()).min(1).max(32),defaultModeId:U}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});N({threadId:H,permissionModeId:U}).strict();let W=k().int().safe().nonnegative(),bs=k().finite().nonnegative(),xs=k().finite().min(0).max(100),Ss=N({version:F([z(3),z(4)]).optional(),requestId:D().min(1),turnId:D().min(1).max(1024),outputTokens:W,startedAtMs:W,completedAtMs:W}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Cs=N({version:F([z(2),z(3),z(4)]).optional(),value:bs,turnId:D().min(1).max(1024),at:W}).strict();N({outputTimings:M(Ss).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Cs.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Cs.extend({value:W}).optional()}).strict();let ws=e=>hs.refine(t=>Object.values(t).every(t=>t.length<=e)),Ts=N({composerIndicators:M(N({kind:z(`countdown`),id:D().min(1).max(64),expiresAtUnix:W,label:ws(256).optional(),tooltip:ws(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:W.optional(),cachedInputTokens:W.optional(),cacheWriteInputTokens:W.optional(),outputTokens:W.optional(),outputTokensPerSecond:bs.optional(),sessionOutputTokensPerSecond:bs.optional(),apiOutputTokensPerSecond:bs.optional(),reasoningOutputTokens:W.optional(),totalTokens:W.optional(),totalCostUsd:bs.optional(),totalCredits:bs.optional(),contextUsagePercent:bs.optional(),cacheHitRatePercent:xs.optional(),contextWindowTokens:W.optional(),contextUsedTokens:W.optional(),planFiveHourUsedPercent:xs.optional(),planFiveHourResetsAtUnix:W.optional(),planSevenDayUsedPercent:xs.optional(),planSevenDayResetsAtUnix:W.optional(),sessionCacheHitRatePercent:xs.optional(),timeToFirstOutputMs:W.optional(),latestRequestTimeToFirstOutputMs:W.optional(),costSource:R([`publicPrice`,`native`]).optional(),unpricedModels:M(D().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),Es=k().finite().min(0).max(100),Ds=R([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),Os=N({id:D().min(1).max(256),label:D().min(1).max(256),localizations:ms.optional()}).strict(),ks=N({product:D().min(1),periodType:Ds.optional(),scope:Os.optional(),localizations:ms.optional(),used:k().finite().nonnegative().optional(),limit:k().finite().nonnegative().optional(),unit:D().min(1).max(32).optional(),usagePercent:Es,resetsAt:D().min(1).optional()}).strict(),As=N({availableCount:k().int().safe().positive(),nextExpiresAt:D().min(1).optional(),expiresAt:M(D().min(1)).min(1).max(32).optional()}).strict(),js=N({used:k().finite().nonnegative().optional(),limit:k().finite().nonnegative().optional(),unit:D().min(1).max(32).optional(),label:D().min(1).optional(),scope:Os.optional(),localizations:ms.optional(),usedPercent:Es,resetsAt:D().min(1).optional(),periodType:Ds,productUsage:M(ks).min(1).optional(),resetCredits:As.optional()}).strict(),Ms=N({amount:k().finite().nonnegative(),currency:D().trim().min(1).max(8),label:D().trim().min(1).max(128).optional()}).strict();N({threadId:H,refresh:z(`exact`).optional()}).strict(),N({threadId:H,usage:Ts.nullable(),accountCredits:js.optional(),accountBalance:Ms.optional(),accountCreditsSupported:j().optional()}).strict();let Ns=D().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ps=D().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Fs=R([`priority`,`ultrafast`]),G=N({id:Ps,serviceTier:Fs.optional()}).strict();function Is(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let K=Ns.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Ls=Ns.max(256),Rs=N({id:K,label:Ns.max(256)}).strict(),zs=N({ref:G,label:Ns.max(256),resolvedModelLabel:Ls.optional(),fastModel:G.optional(),supportedThinkingOptionIds:M(K).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function Bs(e,t){if(t)return e?.models.find(e=>Is(e.ref,t)||Is(e.fastModel,t))}let Vs=M(Rs).superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Thinking option IDs must be unique`,path:[r,`id`]}),n.add(i.id)}),Hs=N({models:M(zs),defaultModel:G.optional(),thinkingOptions:Vs,defaultThinkingOptionId:K.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>Is(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>Is(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!Bs(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),Us=N({fork:j(),forkAcrossCwd:j(),rollbackLastTurn:j()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Ws=R([`live`,`atCreate`]),Gs=N({configuration:N({selectModel:j(),selectThinkingOption:j(),selectPermissionMode:j(),permissionModeScope:Ws.default(`live`)}).strict(),history:Us,subagents:N({observe:j(),readTranscript:j()}).strict().optional(),autonomousTurns:N({observe:j()}).strict().optional(),steer:j().optional(),persistentPlan:j().optional()}).strict();N({effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),availableThinkingOptions:Vs.optional(),effectivePermissionModeId:U.optional()}).strict().superRefine((e,t)=>{e.effectiveThinkingOptionId&&e.availableThinkingOptions&&!e.availableThinkingOptions.some(({id:t})=>t===e.effectiveThinkingOptionId)&&t.addIssue({code:`custom`,message:`Effective Thinking option must be currently available`,path:[`effectiveThinkingOptionId`]})});let Ks=N({open:z(!0)}).strict();F([N({status:z(`ready`),catalog:Hs,permissionModes:ys.optional(),capabilities:Gs,webUi:Ks.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),N({status:R([`notInstalled`,`unavailable`,`error`]),error:ds}).strict()]),N({harnessId:V,cwd:Ns.max(16384).optional(),refresh:j().optional(),purpose:z(`availability`).optional(),credentialAccess:R([`allow`,`retry`]).optional()}).strict(),N({harnessId:V}).strict(),N({}).strict(),N({threadId:H,model:G}).strict(),N({threadId:H,thinkingOptionId:K}).strict(),N({threadId:H,includeReferenceCapability:j().optional()}).strict(),I(`owner`,[N({owner:z(`codex`),locked:j(),effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),effectivePermissionModeId:U.optional(),history:Us.optional(),supportsThreadReferences:z(!0).optional()}).strict(),N({owner:z(`external`),harnessId:Ns.max(256),transportModelId:Ns.max(8192),effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),availableThinkingOptions:Vs.optional(),effectivePermissionModeId:U.optional(),catalog:Hs.optional(),history:Us,usage:Ts.optional(),locked:z(!0)}).strict()]),N({threadIds:M(H).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let qs=I(`owner`,[N({threadId:H,owner:z(`codex`)}).strict(),N({threadId:H,owner:z(`external`),harnessId:D().max(256).pipe(V)}).strict()]);N({threads:M(qs).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),N({threadId:H,text:D().optional()}).strict(),N({kind:z(`application`),value:D().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),xe}}).pipe(N({expectedTurnId:_s,clientUserMessageId:D().min(1),delivery:R([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),R([`activeTurn`,`newTurn`]),N({delivery:R([`official`,`activeTurn`,`newTurn`])}).strict();let Js=D().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),Ys=Js.pipe(V),Xs=Ys.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Zs=D().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),Qs=Xa().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),$s=N({en:D().max(4096),"zh-CN":D().max(4096).optional()}).strict(),ec=N({commands:M(N({terminal:D().max(256),command:D().max(4096)}).strict()).max(8),before:$s.optional(),after:$s.optional(),downloads:M(N({label:D().max(128),url:Qs}).strict()).max(8).optional()}).strict(),tc={id:Ys,name:D().trim().min(1).max(128),version:D().min(1).max(128),kind:z(`usage`).optional(),iconStyle:N({vector:N({viewBox:D().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:D().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:M(N({d:D().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:R([`evenodd`,`nonzero`]).optional(),fill:D().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:D().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:k().min(0).max(50).optional(),paddingRatio:k().min(0).max(.25).optional()}).strict().optional(),installation:ec.optional(),notice:$s.optional(),launchCommand:z(!0).optional(),links:N({website:Qs.optional(),documentation:Qs.optional(),installation:Qs.optional()}).strict().optional()};N({manifestVersion:z(1),...tc,adapterApiVersion:k().int().positive(),entry:Zs,icon:Zs.optional()}).strict();let nc=D().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),rc=N({...tc,icon:nc.optional()}).strict();N({}).strict(),N({plugins:M(rc.extend({id:Xs})).max(128)}).strict(),N({version:z(1),enabled:M(Ys).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let ic=Js,ac=R([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),oc=R([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),sc=D().trim().min(1).max(128);function cc(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let lc=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),uc=Zs.refine(e=>cc(e)!==void 0&&lc(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),dc=D().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Xa({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function fc(e){return P({en:e,"zh-CN":e})}let pc=fc(D().trim().min(1)),mc=M(oc).max(oc.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),hc=M(ac).max(ac.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),gc={key:D().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:pc,description:pc.optional()},_c={...gc,step:k().positive().optional(),default:k().optional()},vc=P({value:D(),label:pc}),yc=I(`type`,[P({...gc,type:z(`boolean`),default:j().optional()}),P({...gc,type:z(`string`),placeholder:pc.optional(),default:D().optional()}),P({..._c,type:z(`number`),min:k().optional(),max:k().optional()}),P({..._c,type:z(`range`),min:k(),max:k()}),P({...gc,type:z(`select`),options:M(vc).min(1),default:D().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),bc=N({manifestVersion:A().positive(),id:ic,name:F([sc,fc(sc)]),version:D().min(1).max(128),desktopApi:A().positive()}).passthrough().extend({manifestVersion:z(1),desktopApi:z(1),description:P({en:D().max(4096),"zh-CN":D().max(4096).optional()}).optional(),author:D().trim().min(1).max(128).optional(),repository:dc.optional(),details:P({en:D().max(16384),"zh-CN":D().max(16384).optional()}).optional(),icon:uc.optional(),screenshots:M(uc).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:P({script:Zs,style:Zs.optional()}).optional(),backend:P({script:Zs.refine(lc)}).optional(),slots:hc.default(()=>[]),settingsSchema:M(yc).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:mc.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),xc=D().regex(/^[a-f0-9]{64}$/u),Sc=P({state:R([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:xc.optional(),error:D().optional(),conflictWith:ic.optional()});P({controllerPid:A().positive(),targetId:D().nullable(),updatedAt:Sa(),handledReloadToken:Ja().optional(),extensions:L(D(),Sc),surfaces:L(D(),Sc).optional()});let Cc=R([`official`,`community`]);function wc(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Tc=dc.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||wc(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),Ec=P({id:ic,version:D().trim().min(1).max(128),name:pc.extend({en:sc,"zh-CN":sc}),description:fc(D().trim().min(1).max(4096)),details:fc(D().trim().min(1).max(16384)).optional(),author:D().trim().min(1).max(128),repository:dc,stars:k().int().min(0).optional(),downloads:k().int().min(0).optional(),categories:mc.optional(),trustTier:Cc.default(`community`),icon:dc.optional(),screenshots:M(dc).max(4).optional(),downloadUrl:Tc,sha256:xc,slots:hc.optional(),publishedAt:D().optional(),updatedAt:D().optional(),minCodexHostVersion:D().optional()});P({schemaVersion:z(1),generatedAt:D(),extensions:M(Ec).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Dc=D().trim().min(1).max(128),Oc=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,kc=ic.refine(e=>!Oc.test(e),`Reserved extension ID`),Ac=R([`desktop`,`web`]),jc=xc,Mc=Ja(),Nc=Zs.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Oc.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),Pc=bc.shape,Fc=(e,t=0)=>P({en:D().trim().min(t).max(e),"zh-CN":D().trim().min(t).max(e)}),Ic=e=>Nc.refine(t=>t.endsWith(e),`Expected a ${e} file`),Lc=Ic(`.mjs`),Rc=Ic(`.css`).optional(),zc=e=>e.normalize(`NFC`).toLowerCase(),Bc=P({manifestVersion:z(2),id:kc,name:Fc(128,1),version:D().trim().min(1).max(128),description:Fc(4096),details:Fc(16384).optional(),author:Pc.author,repository:Pc.repository,icon:Pc.icon.refine(e=>e===void 0||Nc.safeParse(e).success),screenshots:Pc.screenshots.refine(e=>e===void 0||e.every(e=>Nc.safeParse(e).success)),categories:Pc.categories,settingsSchema:Pc.settingsSchema,slots:Pc.slots.removeDefault().optional(),page:P({apiVersion:z(1),entry:Lc,style:Rc,title:Fc(128,1).optional()}).optional(),widget:P({apiVersion:z(1),entry:Lc,style:Rc}).optional(),desktop:P({apiVersion:z(1),script:Ic(`.js`),style:Rc}).optional(),web:P({apiVersion:z(1),entry:Lc.optional(),style:Rc}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:P({apiVersion:z(1),entry:Lc}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||zc(e)!==zc(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Vc({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let Hc=Dc,q=A().nonnegative(),Uc=P({revision:q,enabled:M(kc).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)}),{downloadUrl:Wc,...Gc}=Ec.shape,Kc=N({...Gc,id:kc,format:z(`codexhost`),targets:M(Ac).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:P({page:A().positive().optional(),widget:A().positive().optional(),desktop:A().positive().optional(),web:A().positive().optional(),backend:A().positive().optional()}),downloadUrl:Wc.refine(e=>e.startsWith(`https://`),`Expected HTTPS`)}).refine(({targets:e,apis:t})=>{let n=Vc({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);N({schemaVersion:z(2),generatedAt:D().min(1),extensions:M(Kc).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:dc,fetchedAt:Sa(),cached:j()});let qc={id:kc},Jc={...qc,activationId:Mc,digest:jc},Yc={...qc,activationId:Jc.activationId.optional()},Xc=D().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),Zc=D().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function Qc(e){return D().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let $c=P({type:z(`github`),repository:D().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Zc.optional(),tag:Zc.optional(),asset:D().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Nc.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),el=F([P({type:z(`catalog`),...qc}),$c,P({type:z(`zip`),base64:Qc(67108864).min(4)}),P({type:z(`zip`),localZipPath:Xc}),P({type:z(`localDir`),localDir:Xc})]),tl=I(`type`,[P({type:z(`catalog`),...qc}),$c,P({type:z(`zip`)}),P({type:z(`localDir`)})]),nl=P({...Jc,manifest:Bc,installedAt:Sa(),source:tl.optional()}),rl=e=>D().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),il={desktopConflictWith:kc.optional()},al=R([`none`,`inactive`,`starting`,`running`,`failed`]),ol=I(`state`,[nl.extend({state:z(`valid`),enabled:j(),...il,iconDataUrl:rl(131072).optional(),screenshotDataUrls:M(rl(524288)).max(4).optional(),backendState:al.optional(),backendError:D().optional()}),P({state:R([`invalid`,`incompatible`]),id:D().min(1),enabled:j(),error:D()})]);P({revision:q,configuration:Uc,diagnostics:M(D()),extensions:M(ol)}),P({revision:q,extensions:M(nl.extend({...il,settingsRevision:q})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`},sl=Object.freeze(Object.values(J));new Set(sl),P({});let cl={expectedRevision:q};P({...qc,...cl}),nl.extend({replaced:j()}),I(`state`,[P({state:z(`saved`),configuration:Uc}),P({state:z(`revision-conflict`),revision:q})]),P({...Yc,digest:Jc.digest.optional(),path:Nc}),P({mimeType:D().min(1),base64:Qc(16777216),digest:Jc.digest}),P({settingsRevision:q,values:us}),J.list,J.snapshot,J.catalog,P({forceRefresh:j().optional()}),J.install,P({source:el}),J.update,P({...qc,expectedDigest:Jc.digest,expectedActivationId:Jc.activationId.optional(),source:el.optional()}),J.enable,J.disable,J.uninstall,P({...qc,removeData:j().optional(),expectedDigest:Jc.digest.optional()}),P({...qc,removed:j()}),J.recover,P({expectedRevision:cl.expectedRevision.optional()}),J.asset,J.settingsGet,P(Yc),J.settingsSet,P({...Yc,expectedSettingsRevision:q,values:us}),J.backendInvoke,P({...Yc,method:Hc,params:B.optional()}),P({result:B}),N({threadId:H}).strict(),N({confirmed:j()}).strict(),[...sl],N({sections:M(N({id:D().min(1),name:D().min(1),threads:M(us)}).strict())}).strict(),N({threadId:D().min(1).max(1024),sectionId:D().min(1).max(1024).nullable()}).strict(),N({threadIds:M(D().min(1))}).strict(),N({threadId:D().min(1).max(1024),pinned:j()}).strict(),N({}).strict(),N({parents:L(D().min(1),D().min(1))}).strict(),N({prompt:D().max(16384).optional()}).strict(),N({projects:M(N({id:D(),name:D(),rootPaths:M(D())})),assignments:L(D(),D()),projectless:M(D()),pinned:M(D())});let ll=L(D(),yo()),ul=N({epoch:D().uuid(),sequence:k().int().nonnegative()});I(`type`,[N({type:z(`skills-changed`),cursor:ul,cwd:D().optional()}),N({type:z(`harness-inspection-changed`),cursor:ul,harnessId:D().min(1)}),N({type:z(`display-settings-changed`),cursor:ul}),N({type:z(`preferences-changed`),cursor:ul,revision:k().int().nonnegative()}),N({type:z(`extensions-changed`),cursor:ul,revision:q}),N({type:z(`hello`),version:z(1),cursor:ul,reset:j()}),N({type:z(`changed`),cursor:ul,threadId:D().min(1),method:D().min(1)})]);let dl=I(`type`,[N({type:z(`text`),id:D(),prompt:D(),secret:j().optional(),optional:j().optional()}),N({type:z(`choice`),id:D(),prompt:D(),multiple:j(),allowOther:j(),optional:j().optional(),options:M(N({value:D(),label:D(),description:D().optional()}))})]),fl=I(`type`,[N({type:z(`approval`),title:D(),description:D().optional(),subject:yo().optional(),actions:M(N({id:D(),label:D(),effect:D()}))}),N({type:z(`question`),title:D().optional(),questions:M(dl)})]),pl=N({requestId:F([D(),k().int()]),threadId:D(),kind:R([`approval`,`question`]),interaction:fl,request:ll}),ml=N({id:D().min(1),clientUserMessageId:D().min(1),input:M(ll),presentationInput:M(ll).nullable().optional()}).passthrough();N({fields:M(N({path:M(F([D(),k().int().nonnegative()])),originalLength:k().int().nonnegative()}))});let hl=N({id:D().min(1),status:D().min(1),codexhostTurnOutcome:N({status:z(`unknown`),reason:D()}).optional(),items:M(N({id:D().min(1),type:D().min(1)}).passthrough()),codexhostFileOperations:M(N({beforeItemId:D().nullable(),item:N({id:D().min(1),type:D().min(1)}).passthrough()})).optional(),error:N({message:D().optional()}).passthrough().nullable().optional(),fingerprint:D().min(1).optional(),unchanged:z(!0).optional()}).passthrough(),gl=N({id:D().min(1).max(512),fingerprint:D().min(1).max(128)});N({threadId:D().min(1),knownTurns:M(gl).max(64).optional(),truncateToolOutput:j().optional()});let _l=N({harnessId:D().min(1),nativeSessionId:D().min(1)});N({cursor:ul,activeTurnId:D().min(1).nullable().optional(),command:N({name:D().min(1),turn:hl,subsequentTurnId:D().min(1).optional()}).optional(),thread:N({id:D().min(1),cwd:D(),modelProvider:D().min(1),createdAt:k(),updatedAt:k(),status:N({type:D()}).passthrough(),name:D().nullable().optional(),preview:D().optional(),codexhostImportSource:_l.optional(),turns:M(hl).length(0)}).passthrough(),turnsPage:N({data:M(hl).max(5),nextCursor:D().nullable()}),configuration:N({native:N({model:D().min(1).max(1024).optional(),reasoningEffort:D().min(1).max(128).optional()}).optional(),effectiveModel:G.optional(),effectiveThinkingOptionId:K.optional(),effectivePermissionModeId:U.optional()}),queue:N({items:M(ml),pausedReason:R([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:M(pl)}),N({version:z(1),owner:z(`service`).optional(),pid:k().int().positive(),port:k().int().min(1).max(65535),token:D().regex(/^[0-9a-f]{64}$/u),startedAt:k(),epoch:D().uuid()}),N({epoch:D().uuid(),threadId:D().min(1),requestId:F([D(),k().int()]),result:ll}),N({includeArchived:j().optional(),officialCursor:N({live:D().nullable(),archived:D().nullable().optional()}).strict().optional()}).strict(),N({threads:M(us),ownership:M(qs),archivedThreadIds:M(H),officialCursor:N({live:D().nullable(),archived:D().nullable().optional()}).strict().optional()}).strict();let vl=R([`running`,`waiting`,`idle`,`unknown`]),yl=P({harnessId:V,title:D().optional(),status:vl,archived:j()}),bl=P({revision:A().nonnegative(),parents:L(H,H),nodes:L(H,yl),truncated:j()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,nodes:t})=>Object.entries(e).every(([e,n])=>Object.hasOwn(t,e)&&Object.hasOwn(t,n)),`Missing Thread tree node`),xl=D().min(1).max(128);P({});let Sl=P({subscriptionId:xl});P({}),Sl.extend({snapshot:bl});let Cl=D().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);N({available:j()}).strict(),N({path:D().min(1),mimeType:Cl}).strict();let wl=R([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);I(`ok`,[N({ok:z(!0),text:D()}).strict(),N({ok:z(!1),error:N({code:wl}).strict()}).strict()]),N({threadId:H.optional(),cwd:D().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Tl=N({name:D().min(1).regex(/^[^\s[\]]+$/u),description:D().optional(),path:D().min(1),scope:R([`project`,`global`]),source:D().min(1)}).strict();N({revision:k().int().nonnegative(),complete:j(),skills:M(Tl),warnings:M(D()).optional()}).strict(),N({cwd:D().min(1).optional()}).strict();let El=N({kind:R([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:D().min(1)}).strict(),Dl=I(`status`,[N({status:z(`not-installed`)}),N({status:z(`not-running`)}),N({status:z(`not-logged-in`)}),N({status:z(`https-disabled`)}),N({status:z(`not-serving`),command:D()}),N({status:z(`occupied`),target:D()}),N({status:z(`serving`),url:D(),funnel:j()}),N({status:z(`error`),message:D()})]);N({state:Dl,error:D().optional()}).strict();let Ol=I(`status`,[N({status:z(`on`)}),N({status:z(`off`)}),N({status:z(`invalid`),reason:D()})]),kl=N({lan:j(),autostart:Ol}).strict(),Al=N({expiresAt:D().optional(),issuing:j(),failure:N({detail:D().optional(),retryAt:D(),paused:j()}).optional()}),jl=I(`status`,[N({status:z(`off`),reason:R([`invite`,`name-taken`,`banned`]).optional()}),N({status:z(`connecting`),reason:R([`full`,`unreachable`]).optional()}),N({status:z(`connected`),url:D(),certificate:Al}),N({status:z(`missing-certificate`),url:D(),certificate:Al}),N({status:z(`stopped`),reason:R([`replaced`,`rejected`,`unsupported-version`])})]);D().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),D().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let Ml=R([`official`,`self-hosted`]);N({secret:D().min(1),lastUsedAt:k().nullable(),networkUrls:M(El),directCandidates:M(El).optional(),tailscale:Dl,background:kl.optional(),relay:N({state:jl,enabled:j(),kind:Ml,officialHost:D(),customHost:D().optional(),officialHostname:D().optional(),customHostname:D().optional(),quotaUntil:D().optional()}).strict().optional()}).strict();let Nl=P({threadId:D().min(1).max(1024),view:R([`result`,`messages`]),from:k().int().min(1).max(2**53-1).optional(),to:k().int().min(1).max(2**53-1).optional()}),Pl=N({id:D().min(1).max(256),harnessId:D().min(1),label:D().min(1).max(512),provider:R([`openai-codex`,`xai`])}).strict(),Fl=D().regex(/^[a-z][a-z0-9-]{0,47}$/),Il=N({name:Fl,source:Pl,importedAt:D()}).strict(),Ll=I(`action`,[N({action:z(`list`)}).strict(),N({action:z(`import`),sourceId:D().min(1).max(256),name:Fl,confirmed:z(!0)}).strict(),N({action:z(`reimport`),sourceId:D().min(1).max(256),name:Fl,confirmed:z(!0)}).strict(),N({action:z(`remove`),name:Fl,confirmed:z(!0)}).strict()]),Rl=N({provider:D().min(1).max(128),type:R([`oauth`,`api_key`,`unknown`]),label:D().min(1).max(512).optional(),vendor:R([`openai-codex`,`xai`]).optional()}).strict();N({sources:M(Pl),targets:M(N({harnessId:D(),providers:M(R([`openai-codex`,`xai`])),imports:M(Il),others:M(Rl).default([])}).strict())}).strict(),N({targetHarnessId:D().min(1).max(128).optional(),request:Ll}).strict(),N({events:j()});let zl=M(P({agent:D().min(1).max(128),section:R([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);P({entries:zl.nullable()}),P({}),P({entries:zl,initializeOnly:j().optional()});let Bl=P({enabled:j(),timeoutMinutes:k().int().min(5).max(1440)});Object.freeze({enabled:!1,timeoutMinutes:10});let Vl=D().regex(/^external$/u),Hl=V.transform(e=>String(e)),Ul=P({model:G.optional(),thinkingOptionId:K.optional(),permissionModeId:U.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),Wl=P({lastHarness:V.optional(),byHarness:L(Hl,Ul)}),Gl=P({model:G.optional(),thinkingOptionId:K.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Kl=P({byHarness:L(Hl,Gl)}),ql=D().min(1).max(1024),Jl=P({idleRelease:Bl.optional(),favorites:L(Hl,M(ql).max(2048)).default({}),newThread:Wl.optional(),delegation:Kl.optional()});P({scope:Vl,revision:k().int().nonnegative(),values:Jl}),P({scope:Vl.default(`external`)});let Yl=I(`kind`,[P({kind:z(`idleRelease`),value:Bl}),P({kind:z(`favorite`),harnessId:V,modelId:ql,enabled:j()}),P({kind:z(`favorites`),harnessId:V,modelIds:M(ql).max(2048)}),P({kind:z(`newThread`),lastHarness:V.optional(),harnessId:V.optional(),configuration:Ul.optional()}),P({kind:z(`delegation`),harnessId:V,configuration:Gl.nullable()})]);P({scope:Vl.default(`external`),operations:M(Yl).min(1).max(256),initializeOnly:j().optional(),expectedRevision:k().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),P({version:z(1),revision:k().int().nonnegative(),scopes:L(Vl,Jl)});let Xl=k().finite().nonnegative(),Zl=P({input:Xl,output:Xl,cacheRead:Xl.optional(),cacheWrite:Xl.optional(),cacheWrite1h:Xl.optional()}),Ql=D().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);P({path:D(),entries:M(P({key:D(),price:Zl})),error:D().nullable()}),P({}),P({key:Ql,price:Zl.nullable(),previousKey:Ql.optional()}),P({model:Ql});let $l=P({official:j().optional(),canonicalModelId:D().min(1).optional(),provider:D().min(1).max(512),model:D().min(1).max(512),price:Zl});P({price:Zl.nullable(),suggestions:M($l).max(6).optional()});let eu=[`today`,`7d`,`30d`,`90d`,`all`],Y=k().int().min(0).max(2**53-1),tu=D().regex(/^\d{4}-\d{2}-\d{2}$/u),X=D().min(1).max(128),nu=D().min(1).max(512),ru=D().min(1).max(4096);P({range:R(eu),timeZone:D().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:X.optional(),model:nu.nullable().optional(),project:ru.nullable().optional(),date:tu.optional()});let iu=P({requests:Y,inputTokens:Y,cachedInputTokens:Y,cacheWriteInputTokens:Y,cacheKnownInputTokens:Y,cacheHitCachedInputTokens:Y,cacheHitInputTokens:Y,outputTokens:Y,reasoningOutputTokens:Y,costUsd:k().finite().min(0),unpricedRequests:Y,unmeteredRequests:Y}),au=iu.shape,ou=P({harness:X,sessionId:D().min(1).max(512),project:ru.nullable(),title:D().min(1).max(200).optional(),models:M(nu).max(16),firstAtMs:Y,lastAtMs:Y,...au});P({range:R(eu),from:tu.nullable(),to:tu,filters:P({harness:X.nullable(),model:nu.nullable(),unknownModel:j(),project:ru.nullable(),unknownProject:j(),date:tu.nullable()}),reading:P({complete:j(),sources:Y,read:Y}),failures:M(P({harness:X,message:D().max(2048)})).max(256),options:P({harnesses:M(X).max(256),models:M(nu.nullable()).max(4096),projects:M(ru.nullable()).max(4096)}),modelLabels:M(P({harness:X,model:nu,label:nu})).max(4096).optional(),credits:M(P({harness:X,model:nu.nullable(),credits:k().finite().min(0),reportedRequests:Y,requests:Y})).max(4096).optional(),totals:iu,daily:M(P({date:tu,harness:X,...au})).max(2e5),hourly:M(P({weekday:k().int().min(0).max(6),hour:k().int().min(0).max(23),...au})).max(168),byHarness:M(P({harness:X,...au})).max(256),byModel:M(P({model:nu.nullable(),...au,harnessPricedRequests:Y})).max(4096),byProject:M(P({project:ru.nullable(),...au})).max(4096),sessions:M(ou).max(100),recentSessions:M(ou).max(100).optional()}),N({threadId:H}),N({discarded:j()});let su=I(`type`,[N({id:D().min(1),type:z(`choice`),prompt:D(),options:M(N({value:D().min(1),label:D(),description:D().optional()})).min(1),multiple:j(),allowOther:j(),optional:j()}),N({id:D().min(1),type:z(`text`),prompt:D(),multiline:j(),secret:z(!1),optional:j(),placeholder:D().optional(),prefill:D().optional()})]),cu=N({interactionId:D().min(1),turnId:D().min(1),title:D().optional(),questions:M(su).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});P({threadId:D().min(1)}),N({questions:M(cu)}),P({threadId:D().min(1),turnId:D().min(1),interactionId:D().min(1),answers:L(D(),M(D())),cancelled:j().default(!1)}),N({accepted:z(!0)});let lu=`codexhostActiveTurnId`,uu=/* @__PURE__ */ new Set([lu,`codexhostTurnChanges`,`codexhostToolOutput`]),du=N({path:D(),oldText:D().nullable(),newText:D()});N({sessionId:D().min(1),turn:k().int().nonnegative(),path:D().min(1).optional()}),N({diffs:M(du)}),P({}),P({}),N({reference:N({sessionId:D().min(1),epoch:D().min(1),turn:k().int().nonnegative(),seq:k().int().nonnegative(),callId:D().min(1),part:k().int().nonnegative(),version:D().min(1)}),length:k().int().nonnegative(),bytes:k().int().nonnegative()}),P({title:D().trim().min(1).max(200),type:R([`info`,`warning`,`danger`]),body:D().trim().min(1).max(16384)}),P({}),P({url:D().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status`.split(`.`));let fu=R([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),pu=R([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);P({threadId:D(),title:D(),harnessId:D(),state:fu,reason:pu,inactiveMs:k().nonnegative()}),P({threadId:H,turnId:_s});let mu=N({email:D().trim().min(1).max(320).optional(),label:D().trim().min(1).max(256).optional(),plan:D().trim().min(1).max(128).optional(),credits:js.optional(),balance:Ms.optional()}).strict();function hu(e){return e.refine(e=>{let t=e;return t.credits!==void 0||t.balance!==void 0},{message:`Account must report either credits or a balance`})}let gu=hu(mu),_u={harnessId:V,harnessName:D().trim().min(1).max(128)},vu=N(_u).strict();N({}).strict(),N({sources:M(vu).max(128)}).strict(),N({harnessId:V,refresh:j().optional()}).strict(),N({..._u,account:gu.nullable(),accounts:M(gu).max(8).optional()}).strict(),N({refresh:j().optional()}).strict(),N({accounts:M(hu(mu.extend(_u))).max(128)}).strict(),N({harnessId:Xs,model:G.optional(),thinkingOptionId:K.optional(),permissionModeId:U.optional(),prewarm:z(!0).optional()}).strict();let yu=D().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);N({harnessId:Xs}).strict().extend({path:yu.nullable()}),N({path:yu.nullable(),restartRequired:j()}).strict(),N({harnessId:V,action:R([`check`,`update`,`install`]),confirmedVersion:D().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let bu=N({currentVersion:D().min(1).max(128),latestVersion:D().min(1).max(128),updateAvailable:j(),canUpdate:j(),latestVerifiedVersion:D().min(1).max(128).optional(),confirmationRequired:z(!0).optional(),versionKind:R([`cli`,`application`]).optional(),manualUpdateUrl:Xa().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:D().max(2048).optional(),messageCode:D().min(1).max(128).optional(),notice:hs.optional(),latestVersionKind:R([`unknown`,`tracking-branch`]).optional()}).strict();N({taskId:D().uuid()}).strict(),I(`status`,[N({taskId:D().uuid(),status:z(`running`)}).strict(),N({taskId:D().uuid(),status:z(`succeeded`),result:bu}).strict(),N({taskId:D().uuid(),status:z(`failed`),error:N({code:k().int(),message:D().min(1).max(2048)}).strict()}).strict()]);let xu=D().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Su=D().trim().min(1),Cu=R([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),wu=N({accountId:xu,label:Su.max(256),email:D().email().max(320).optional(),planType:Cu.optional()}).strict(),Tu=R([`ready`,`unavailable`]);N({version:z(2),currentAccountId:xu.nullable(),phase:Tu,revision:k().int().nonnegative(),instanceId:Su.max(1024).optional(),accounts:M(wu).max(1)}).strict(),N({accountId:xu,refresh:j().optional()}).strict(),N({accountId:xu,usage:Ts.nullable(),accountCredits:js.optional(),freshness:R([`live`,`cached`]),observedAt:D().datetime().nullable()}).strict();let Eu=1e3,Du=D().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Ou=Du.max(1024),ku=N({nativeSessionId:Ou,title:Du.max(4096).nullable(),updatedAt:k().int().nonnegative().max(864e13),cwd:Du.max(16384),running:j().nullable()}).strict();N({}).strict(),N({harnesses:M(N({harnessId:Xs,name:Du.max(128)}).strict()).max(128)}).strict(),N({harnessId:Xs,query:D().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:k().int().nonnegative().safe().optional(),limit:k().int().min(1).max(Eu).optional()}).strict(),N({candidates:M(ku).max(Eu),total:k().int().nonnegative().safe()}).strict(),N({harnessId:Xs,nativeSessionId:Ou}).strict(),N({threadId:Du.max(1024).pipe(H)}).strict();let Au=D().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),ju=Ou,Mu=ku;N({}).strict(),N({candidates:M(Mu).max(1e3)}).strict(),N({nativeSessionId:ju}).strict(),N({threadId:Au.max(1024).pipe(H)}).strict(),N({threadId:H,lastTurnId:_s}).strict(),N({threadId:H}).strict();let Nu=D().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();N({commands:M(N({id:Nu,invocation:D().min(1).max(128),label:D().trim().min(1).max(128),description:D().trim().min(1).max(512).optional(),localizations:ms.optional(),argumentMode:R([`none`,`text`]),kind:R([`command`,`skill`]).optional()}).strict()),warnings:M(D().min(1)).optional(),source:R([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),N({harnessId:V,cwd:D().min(1).optional()}).strict(),N({threadId:H}).strict(),N({threadId:H,commandId:Nu,turnId:_s.optional(),arguments:us.optional()}).strict(),N({accepted:z(!0),turnId:_s.optional()}).strict();let Pu=z(`2.0`).optional(),Z=xo().optional(),Fu=D().min(1),Iu=F([D(),k().int()]),Lu=N({code:k().int(),message:D(),data:B.optional()}).catchall(B).superRefine(as([`data`]));F([N({jsonrpc:Pu,id:Iu,method:Fu,params:B.optional(),result:Z,error:Z}).catchall(B).superRefine(as([`jsonrpc`,`params`,`result`,`error`])),N({jsonrpc:Pu,id:Z,method:Fu,params:B.optional(),result:Z,error:Z}).catchall(B).superRefine(as([`jsonrpc`,`id`,`params`,`result`,`error`])),N({jsonrpc:Pu,id:Iu,method:Z,params:Z,result:B,error:Z}).catchall(B).superRefine(as([`jsonrpc`,`method`,`params`,`error`])),N({jsonrpc:Pu,id:Iu,method:Z,params:Z,result:Z,error:Lu}).catchall(B).superRefine(as([`jsonrpc`,`method`,`params`,`result`]))]);let Ru=D().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});P({harnessId:V,nativeSessionId:Ru,locator:B.optional(),formatVersion:z(1)}).superRefine(as([`locator`])),P({harnessId:V,nativeSessionId:Ru,nativeTurnKey:Ru,formatVersion:z(1)}),P({harnessId:V,nativeSessionId:Ru,checkpointId:Ru,locator:B.optional(),formatVersion:z(1)}).superRefine(as([`locator`]));let zu=D().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Bu=R([`npm`,`windows-installer`,`macos-dmg`]),Vu=P({version:zu,installation:Bu,phase:R([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:k().int().nonnegative(),downloadedBytes:k().int().nonnegative().optional(),totalBytes:k().int().positive().optional(),error:D().min(1).max(500).nullable(),serviceStopOutput:D().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});P({});let Hu=D().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`);P({currentVersion:zu,installation:Bu.nullable(),latestVersion:zu.nullable(),updateAvailable:j(),installationAvailable:j(),releaseNotes:D().min(1).max(2e4).nullable(),releaseNotesUrl:Hu.nullable(),status:Vu.nullable(),error:D().min(1).max(500).nullable()}),P({status:Vu}),P({status:Vu.nullable()});let Uu=P({icon:D().min(1).max(16).optional(),title:D().min(1).max(120),body:D().min(1).max(1200),contributors:M(D().min(1).max(39)).max(30)}),Wu=P({summary:D().min(1).max(600).optional(),themes:M(Uu).min(1).max(12)}),Gu=P({version:zu,publishedAt:Sa(),url:D().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Wu.nullable(),en:Wu.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});P({manual:j().optional()}),P({announcement:Gu.nullable(),unread:j()}),P({version:zu}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Ku=R([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);N({runningVersion:D().nullable(),installedVersion:D().nullable(),restartRequired:j(),remote:j(),updateSupported:j(),update:N({phase:Ku,targetVersion:D().nullable(),error:D().nullable()})});let qu=N({version:D().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();N({hostname:D().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable(),action:R([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:j().optional(),version:D().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),N({state:R([`installed`,`not-installed`])}).strict();let Q=D().min(1).max(1024),Ju={hostId:Q.regex(/^remote-(?:ssh(?:-|:)|control:)/u)},$={...Ju,threadId:Q},Yu=D().min(1).max(8e3),Xu={text:Yu,requestId:Q};I(`accepted`,[N({accepted:z(!0),startQueuedItemId:Q.optional()}),N({accepted:z(!1),code:R([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:D()})]),I(`available`,[N({available:z(!1)}),N({available:z(!0),items:M(N({id:Q,clientUserMessageId:Q,preview:D().max(801)})).max(100)})]);let Zu=I(`kind`,[P({kind:z(`hosts`)}),P({kind:z(`create`),...Ju,cwd:D().min(1).max(8192),epoch:Q}),P({kind:z(`projectHarnesses`),...Ju,epoch:Q}),P({kind:z(`inspectHarness`),...Ju,epoch:Q,cwd:D().min(1).max(8192),harnessId:Q}),P({kind:z(`startSelected`),...Ju,epoch:Q,cwd:D().min(1).max(8192),harnessId:Q,model:D().min(1).max(4096),serviceTier:R([`priority`,`ultrafast`]).optional(),reasoningEffort:Q.optional()}),P({kind:z(`status`),...$}),P({kind:z(`list`),...Ju,cursor:D().nullable(),archived:j(),includeLoaded:z(!0).optional()}),P({kind:z(`read`),...$,page:P({cursor:D().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:R([`asc`,`desc`]).optional(),limit:k().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),P({kind:z(`usage`),...$,epoch:Q}),P({kind:z(`configure`),...$,epoch:Q,modelId:Q.optional(),serviceTier:Fs.optional(),thinkingOptionId:Q.optional(),permissionModeId:Q.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),P({kind:z(`prompt`),...$,epoch:Q,text:Yu,requestId:Q.optional()}),P({kind:z(`queue`),...$,epoch:Q}),P({kind:z(`delivery`),...$,epoch:Q,action:I(`kind`,[P({kind:z(`enqueue`),...Xu}),P({kind:z(`steer`),...Xu,turnId:Q}),P({kind:z(`remove`),itemId:Q}),P({kind:z(`start`),itemId:Q,onlyIfHead:z(!0).optional()})])}),P({kind:z(`interrupt`),...$,epoch:Q,turnId:Q}),P({kind:z(`rename`),...$,epoch:Q,name:D().min(1).max(512)}),P({kind:z(`archive`),...$,epoch:Q,archived:j()}),P({kind:z(`respond`),...$,epoch:Q,requestId:F([Q,k().int()]),result:L(D(),yo())})]),Qu=D().min(1).max(1024),$u=N({hostId:Qu,displayName:D().min(1).max(1024),source:R([`codex-managed`,`discovered`]),sshAlias:D().max(1024).nullable(),sshHost:D().min(1).max(1024),sshPort:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable(),autoConnect:j(),connectionAnalyticsId:D().max(1024).optional()}),ed=P({displayName:D().min(1).max(1024),hostname:D().min(1).max(1024),sshPort:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable()});I(`action`,[P({action:z(`session`),operation:Zu}),P({action:z(`list`)}),P({action:z(`catalog`)}),P({action:z(`read-thread`),hostId:Qu.refine(e=>e!==`local`),input:Nl}),P({action:z(`save`),draft:ed,previous:$u.nullable()}),P({action:z(`remove`),previous:$u}),P({action:z(`connect`),hostId:Qu,enabled:j()}),P({action:z(`state`),hostId:Qu}),P({action:z(`runtime`),hostId:Qu}),P({action:z(`update`),hostId:Qu.refine(e=>e!==`local`),version:qu.shape.version})]),F([P({result:B}),P({error:P({code:k().int(),message:D()})})]),P({prompt:D().trim().min(1).max(2e3),cwd:D().max(4096).nullable()}),D().trim().min(1).max(60).nullable();let td=D().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),nd=F([D(),N({en:D()}).catchall(D())]),rd=N({title:nd.optional(),description:nd.optional(),icon:D().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:D().optional()});N({extensions:M(N({id:td,name:D().min(1).max(214),version:D().min(1).max(128),format:z(`dsh`),supportedTargets:ko([z(`web`)]),enabledTargets:M(z(`web`)).max(1),source:D().min(1).max(4096),projectUrl:D().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:D(),meta:rd.optional(),loadError:D().optional()})),loadedIds:M(td),safeMode:j(),storeError:D().optional()});let id=D().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);N({spec:D().trim().min(1).max(4096),registry:id.optional()}).strict(),N({id:td,enabled:j()}).strict(),N({id:td}).strict(),z(1);function ad(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
|
|
122
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}}function qi(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Yi(t,`input`,e.processors),output:Yi(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function w(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return w(r.element,n);if(r.type===`set`)return w(r.valueType,n);if(r.type===`lazy`)return w(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return w(r.innerType,n);if(r.type===`intersection`)return w(r.left,n)||w(r.right,n);if(r.type===`record`||r.type===`map`)return w(r.keyType,n)||w(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:w(r.in,n)||w(r.out,n);if(r.type===`object`){for(let e in r.shape)if(w(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(w(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(w(e,n))return!0;return!!(r.rest&&w(r.rest,n))}return!1}let Ji=(e,t={})=>n=>{let r=Gi({...n,processors:t});return C(e,r),Ki(r,e),qi(r,e)},Yi=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Gi({...i??{},target:a,io:t,processors:n});return C(e,o),Ki(o,e),qi(o,e)},Xi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Zi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Xi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Qi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},$i=(e,t,n,r)=>{n.type=`boolean`},ea=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ta=(e,t,n,r)=>{n.not={}},na=(e,t,n,r)=>{let i=e._zod.def,a=Te(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ra=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ia=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},aa=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},oa=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=C(a.element,t,{...r,path:[...r.path,`items`]})},sa=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=C(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=C(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ca=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>C(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},la=(e,t,n,r)=>{let i=e._zod.def,a=C(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=C(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ua=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>C(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?C(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},da=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=C(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=C(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=C(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},fa=(e,t,n,r)=>{let i=e._zod.def,a=C(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},pa=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ma=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},ha=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},ga=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},_a=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;C(o,t,r);let s=t.seen.get(e);s.ref=o},va=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ya=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ba=(e,t,n,r)=>{let i=e._zod.innerType;C(i,t,r);let a=t.seen.get(e);a.ref=i},xa=/*@__PURE__*/ h(`ZodISODateTime`,(e,t)=>{Mn.init(e,t),O.init(e,t)});function Sa(e){return/* @__PURE__ */ ui(xa,e)}let Ca=/*@__PURE__*/ h(`ZodISODate`,(e,t)=>{Nn.init(e,t),O.init(e,t)});function wa(e){return/* @__PURE__ */ di(Ca,e)}let Ta=/*@__PURE__*/ h(`ZodISOTime`,(e,t)=>{Pn.init(e,t),O.init(e,t)});function Ea(e){return/* @__PURE__ */ fi(Ta,e)}let Da=/*@__PURE__*/ h(`ZodISODuration`,(e,t)=>{Fn.init(e,t),O.init(e,t)});function Oa(e){return/* @__PURE__ */ pi(Da,e)}let T=/*@__PURE__*/ h(`ZodError`,(e,t)=>{ot.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>lt(e,t)},flatten:{value:t=>ct(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ee,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ee,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ka=/* @__PURE__ */ ut(T),Aa=/* @__PURE__ */ dt(T),ja=/* @__PURE__ */ ft(T),Ma=/* @__PURE__ */ mt(T),Na=/* @__PURE__ */ gt(T),Pa=/* @__PURE__ */ _t(T),Fa=/* @__PURE__ */ vt(T),Ia=/* @__PURE__ */ yt(T),La=/* @__PURE__ */ bt(T),Ra=/* @__PURE__ */ xt(T),za=/* @__PURE__ */ St(T),Ba=/* @__PURE__ */ Ct(T),Va=/* @__PURE__ */ new WeakMap;function Ha(e,t,n){let r=Object.getPrototypeOf(e),i=Va.get(r);if(i||(i=/* @__PURE__ */ new Set,Va.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let E=/*@__PURE__*/ h(`ZodType`,(e,t)=>(x.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Yi(e,`input`),output:Yi(e,`output`)}}),e.toJSONSchema=Ji(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>ka(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ja(e,t,n),e.parseAsync=async(t,n)=>Aa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ma(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Na(e,t,n),e.decode=(t,n)=>Pa(e,t,n),e.encodeAsync=async(t,n)=>Fa(e,t,n),e.decodeAsync=async(t,n)=>Ia(e,t,n),e.safeEncode=(t,n)=>La(e,t,n),e.safeDecode=(t,n)=>Ra(e,t,n),e.safeEncodeAsync=async(t,n)=>za(e,t,n),e.safeDecodeAsync=async(t,n)=>Ba(e,t,n),Ha(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Ne(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ue(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rs(e,t))},superRefine(e,t){return this.check(is(e,t))},overwrite(e){return this.check(/* @__PURE__ */ Pi(e))},optional(){return Io(this)},exactOptional(){return Ro(this)},nullable(){return Bo(this)},nullish(){return Io(Bo(this))},nonoptional(e){return Ko(this,e)},array(){return M(this)},or(e){return F([this,e])},and(e){return Do(this,e)},transform(e){return Xo(this,Po(e))},default(e){return Ho(this,e)},prefault(e){return Wo(this,e)},catch(e){return Jo(this,e)},pipe(e){return Xo(this,e)},readonly(){return Qo(this)},describe(e){let t=this.clone();return Br.add(t,{description:e}),t},meta(...e){if(e.length===0)return Br.get(this);let t=this.clone();return Br.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Br.get(e)?.description},configurable:!0}),e)),Ua=/*@__PURE__*/ h(`_ZodString`,(e,t)=>{bn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ha(e,`_ZodString`,{regex(...e){return this.check(/* @__PURE__ */ Oi(...e))},includes(...e){return this.check(/* @__PURE__ */ ji(...e))},startsWith(...e){return this.check(/* @__PURE__ */ Mi(...e))},endsWith(...e){return this.check(/* @__PURE__ */ Ni(...e))},min(...e){return this.check(/* @__PURE__ */ Ei(...e))},max(...e){return this.check(/* @__PURE__ */ Ti(...e))},length(...e){return this.check(/* @__PURE__ */ Di(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Ei(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ ki(e))},uppercase(e){return this.check(/* @__PURE__ */ Ai(e))},trim(){return this.check(/* @__PURE__ */ Ii())},normalize(...e){return this.check(/* @__PURE__ */ Fi(...e))},toLowerCase(){return this.check(/* @__PURE__ */ Li())},toUpperCase(){return this.check(/* @__PURE__ */ Ri())},slugify(){return this.check(/* @__PURE__ */ zi())}})}),Wa=/*@__PURE__*/ h(`ZodString`,(e,t)=>{bn.init(e,t),Ua.init(e,t),e.email=t=>e.check(/* @__PURE__ */ Hr(Ga,t)),e.url=t=>e.check(/* @__PURE__ */ Jr(Ya,t)),e.jwt=t=>e.check(/* @__PURE__ */ li(fo,t)),e.emoji=t=>e.check(/* @__PURE__ */ Yr(Za,t)),e.guid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.uuid=t=>e.check(/* @__PURE__ */ Wr(qa,t)),e.uuidv4=t=>e.check(/* @__PURE__ */ Gr(qa,t)),e.uuidv6=t=>e.check(/* @__PURE__ */ Kr(qa,t)),e.uuidv7=t=>e.check(/* @__PURE__ */ qr(qa,t)),e.nanoid=t=>e.check(/* @__PURE__ */ Xr(Qa,t)),e.guid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.cuid=t=>e.check(/* @__PURE__ */ Zr($a,t)),e.cuid2=t=>e.check(/* @__PURE__ */ Qr(eo,t)),e.ulid=t=>e.check(/* @__PURE__ */ $r(to,t)),e.base64=t=>e.check(/* @__PURE__ */ oi(co,t)),e.base64url=t=>e.check(/* @__PURE__ */ si(lo,t)),e.xid=t=>e.check(/* @__PURE__ */ ei(no,t)),e.ksuid=t=>e.check(/* @__PURE__ */ ti(ro,t)),e.ipv4=t=>e.check(/* @__PURE__ */ ni(io,t)),e.ipv6=t=>e.check(/* @__PURE__ */ ri(ao,t)),e.cidrv4=t=>e.check(/* @__PURE__ */ ii(oo,t)),e.cidrv6=t=>e.check(/* @__PURE__ */ ai(so,t)),e.e164=t=>e.check(/* @__PURE__ */ ci(uo,t)),e.datetime=t=>e.check(Sa(t)),e.date=t=>e.check(wa(t)),e.time=t=>e.check(Ea(t)),e.duration=t=>e.check(Oa(t))});function D(e){return/* @__PURE__ */ Vr(Wa,e)}let O=/*@__PURE__*/ h(`ZodStringFormat`,(e,t)=>{S.init(e,t),Ua.init(e,t)}),Ga=/*@__PURE__*/ h(`ZodEmail`,(e,t)=>{Cn.init(e,t),O.init(e,t)}),Ka=/*@__PURE__*/ h(`ZodGUID`,(e,t)=>{xn.init(e,t),O.init(e,t)}),qa=/*@__PURE__*/ h(`ZodUUID`,(e,t)=>{Sn.init(e,t),O.init(e,t)});function Ja(e){return/* @__PURE__ */ Wr(qa,e)}let Ya=/*@__PURE__*/ h(`ZodURL`,(e,t)=>{wn.init(e,t),O.init(e,t)});function Xa(e){return/* @__PURE__ */ Jr(Ya,e)}let Za=/*@__PURE__*/ h(`ZodEmoji`,(e,t)=>{Tn.init(e,t),O.init(e,t)}),Qa=/*@__PURE__*/ h(`ZodNanoID`,(e,t)=>{En.init(e,t),O.init(e,t)}),$a=/*@__PURE__*/ h(`ZodCUID`,(e,t)=>{Dn.init(e,t),O.init(e,t)}),eo=/*@__PURE__*/ h(`ZodCUID2`,(e,t)=>{On.init(e,t),O.init(e,t)}),to=/*@__PURE__*/ h(`ZodULID`,(e,t)=>{kn.init(e,t),O.init(e,t)}),no=/*@__PURE__*/ h(`ZodXID`,(e,t)=>{An.init(e,t),O.init(e,t)}),ro=/*@__PURE__*/ h(`ZodKSUID`,(e,t)=>{jn.init(e,t),O.init(e,t)}),io=/*@__PURE__*/ h(`ZodIPv4`,(e,t)=>{In.init(e,t),O.init(e,t)}),ao=/*@__PURE__*/ h(`ZodIPv6`,(e,t)=>{Ln.init(e,t),O.init(e,t)}),oo=/*@__PURE__*/ h(`ZodCIDRv4`,(e,t)=>{Rn.init(e,t),O.init(e,t)}),so=/*@__PURE__*/ h(`ZodCIDRv6`,(e,t)=>{zn.init(e,t),O.init(e,t)}),co=/*@__PURE__*/ h(`ZodBase64`,(e,t)=>{Vn.init(e,t),O.init(e,t)}),lo=/*@__PURE__*/ h(`ZodBase64URL`,(e,t)=>{Un.init(e,t),O.init(e,t)}),uo=/*@__PURE__*/ h(`ZodE164`,(e,t)=>{Wn.init(e,t),O.init(e,t)}),fo=/*@__PURE__*/ h(`ZodJWT`,(e,t)=>{Kn.init(e,t),O.init(e,t)}),po=/*@__PURE__*/ h(`ZodNumber`,(e,t)=>{qn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r),Ha(e,`ZodNumber`,{gt(e,t){return this.check(/* @__PURE__ */ Si(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},min(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},lt(e,t){return this.check(/* @__PURE__ */ bi(e,t))},lte(e,t){return this.check(/* @__PURE__ */ xi(e,t))},max(e,t){return this.check(/* @__PURE__ */ xi(e,t))},int(e){return this.check(A(e))},safe(e){return this.check(A(e))},positive(e){return this.check(/* @__PURE__ */ Si(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Ci(0,e))},negative(e){return this.check(/* @__PURE__ */ bi(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ xi(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ wi(e,t))},step(e,t){return this.check(/* @__PURE__ */ wi(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function k(e){return/* @__PURE__ */ mi(po,e)}let mo=/*@__PURE__*/ h(`ZodNumberFormat`,(e,t)=>{Jn.init(e,t),po.init(e,t)});function A(e){return/* @__PURE__ */ hi(mo,e)}let ho=/*@__PURE__*/ h(`ZodBoolean`,(e,t)=>{Yn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r)});function j(e){return/* @__PURE__ */ gi(ho,e)}let go=/*@__PURE__*/ h(`ZodNull`,(e,t)=>{Xn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(e,t,n,r)});function _o(e){return/* @__PURE__ */ _i(go,e)}let vo=/*@__PURE__*/ h(`ZodUnknown`,(e,t)=>{Zn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function yo(){return/* @__PURE__ */ vi(vo)}let bo=/*@__PURE__*/ h(`ZodNever`,(e,t)=>{Qn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r)});function xo(e){return/* @__PURE__ */ yi(bo,e)}let So=/*@__PURE__*/ h(`ZodArray`,(e,t)=>{er.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),e.element=t.element,Ha(e,`ZodArray`,{min(e,t){return this.check(/* @__PURE__ */ Ei(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Ei(1,e))},max(e,t){return this.check(/* @__PURE__ */ Ti(e,t))},length(e,t){return this.check(/* @__PURE__ */ Di(e,t))},unwrap(){return this.element}})});function M(e,t){return/* @__PURE__ */ Bi(So,e,t)}let Co=/*@__PURE__*/ h(`ZodObject`,(e,t)=>{ar.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sa(e,t,n,r),_(e,`shape`,()=>t.shape),Ha(e,`ZodObject`,{keyof(){return R(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:yo()})},loose(){return this.clone({...this._zod.def,catchall:yo()})},strict(){return this.clone({...this._zod.def,catchall:xo()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Je(this,e)},safeExtend(e){return Ye(this,e)},merge(e){return Xe(this,e)},pick(e){return Ke(this,e)},omit(e){return qe(this,e)},partial(...e){return Ze(Fo,this,e[0])},required(...e){return Qe(Go,this,e[0])}})});function N(e,t){let n={type:`object`,shape:e??{},...v(t)};return new Co(n)}function P(e,t){return new Co({type:`object`,shape:e,catchall:xo(),...v(t)})}let wo=/*@__PURE__*/ h(`ZodUnion`,(e,t)=>{sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ca(e,t,n,r),e.options=t.options});function F(e,t){return new wo({type:`union`,options:e,...v(t)})}let To=/*@__PURE__*/ h(`ZodDiscriminatedUnion`,(e,t)=>{wo.init(e,t),cr.init(e,t)});function I(e,t,n){return new To({type:`union`,options:t,discriminator:e,...v(n)})}let Eo=/*@__PURE__*/ h(`ZodIntersection`,(e,t)=>{lr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>la(e,t,n,r)});function Do(e,t){return new Eo({type:`intersection`,left:e,right:t})}let Oo=/*@__PURE__*/ h(`ZodTuple`,(e,t)=>{fr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ua(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function ko(e,t,n){let r=t instanceof x;return new Oo({type:`tuple`,items:e,rest:r?t:null,...v(r?n:t)})}let Ao=/*@__PURE__*/ h(`ZodRecord`,(e,t)=>{gr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>da(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function L(e,t,n){return!t||!t._zod?new Ao({type:`record`,keyType:D(),valueType:e,...v(t)}):new Ao({type:`record`,keyType:e,valueType:t,...v(n)})}let jo=/*@__PURE__*/ h(`ZodEnum`,(e,t)=>{_r.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>na(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})}});function R(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new jo({type:`enum`,entries:n,...v(t)})}let Mo=/*@__PURE__*/ h(`ZodLiteral`,(e,t)=>{vr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ra(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function z(e,t){return new Mo({type:`literal`,values:Array.isArray(e)?e:[e],...v(t)})}let No=/*@__PURE__*/ h(`ZodTransform`,(e,t)=>{yr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aa(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(it(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(it(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Po(e){return new No({type:`transform`,transform:e})}let Fo=/*@__PURE__*/ h(`ZodOptional`,(e,t)=>{xr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Fo({type:`optional`,innerType:e})}let Lo=/*@__PURE__*/ h(`ZodExactOptional`,(e,t)=>{Sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ro(e){return new Lo({type:`optional`,innerType:e})}let zo=/*@__PURE__*/ h(`ZodNullable`,(e,t)=>{Cr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bo(e){return new zo({type:`nullable`,innerType:e})}let Vo=/*@__PURE__*/ h(`ZodDefault`,(e,t)=>{wr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ma(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ho(e,t){return new Vo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Uo=/*@__PURE__*/ h(`ZodPrefault`,(e,t)=>{Er.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ha(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wo(e,t){return new Uo({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Go=/*@__PURE__*/ h(`ZodNonOptional`,(e,t)=>{Dr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ko(e,t){return new Go({type:`nonoptional`,innerType:e,...v(t)})}let qo=/*@__PURE__*/ h(`ZodCatch`,(e,t)=>{kr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ga(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jo(e,t){return new qo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let Yo=/*@__PURE__*/ h(`ZodPipe`,(e,t)=>{Ar.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.in=t.in,e.out=t.out});function Xo(e,t){return new Yo({type:`pipe`,in:e,out:t})}let Zo=/*@__PURE__*/ h(`ZodReadonly`,(e,t)=>{Mr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>va(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qo(e){return new Zo({type:`readonly`,innerType:e})}let $o=/*@__PURE__*/ h(`ZodLazy`,(e,t)=>{Pr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ba(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function es(e){return new $o({type:`lazy`,getter:e})}let ts=/*@__PURE__*/ h(`ZodCustom`,(e,t)=>{Fr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ia(e,t,n,r)});function ns(e,t){return/* @__PURE__ */ Vi(ts,e??(()=>!0),t)}function rs(e,t={}){return/* @__PURE__ */ Hi(ts,e,t)}function is(e,t){return/* @__PURE__ */ Ui(e,t)}function as(e){return(t,n)=>{for(let r of e)Object.hasOwn(t,r)&&t[r]===void 0&&n.addIssue({code:`custom`,path:[r],message:`Explicit undefined is not valid JSON`})}}let os=F([D(),k(),j(),_o()]);function ss(e){let t=/* @__PURE__ */ new WeakSet,n=[{value:e,leaving:!1}];try{for(;n.length>0;){let e=n.pop();if(!e)break;if(e.leaving)t.delete(e.value);else if(typeof e.value==`object`&&e.value!==null){if(t.has(e.value))return!1;t.add(e.value),n.push({value:e.value,leaving:!0});for(let t of Object.values(e.value))n.push({value:t,leaving:!1})}}}catch{return!1}return!0}let cs=ns(ss,{message:`JSON value must not contain circular references`}),ls=es(()=>F([os,M(ls),L(D(),ls)])),B=cs.pipe(ls);cs.pipe(M(ls));let us=cs.pipe(L(D(),ls)),ds=P({code:D().min(1),message:D().min(1),retryable:j(),diagnostic:D().min(1).optional(),stage:D().min(1).optional(),durationMs:k().int().nonnegative().optional(),stderrTail:D().min(1).optional()}).superRefine(as([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),fs=D().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),ps=e=>D().min(1).max(e).refine(e=>e.trim().length>0),ms=L(fs,N({label:ps(256).optional(),description:ps(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),hs=L(fs,ps(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),gs=D().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),V=gs.brand(),H=gs.brand(),_s=gs.brand();gs.brand(),gs.brand();let vs=D().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),U=vs.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),ys=N({modes:M(N({id:U,label:vs.max(256),description:vs.max(1024).optional(),dangerous:j().optional(),localizations:ms.optional()}).strict()).min(1).max(32),defaultModeId:U}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});N({threadId:H,permissionModeId:U}).strict();let W=k().int().safe().nonnegative(),bs=k().finite().nonnegative(),xs=k().finite().min(0).max(100),Ss=N({version:F([z(3),z(4)]).optional(),requestId:D().min(1),turnId:D().min(1).max(1024),outputTokens:W,startedAtMs:W,completedAtMs:W}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Cs=N({version:F([z(2),z(3),z(4)]).optional(),value:bs,turnId:D().min(1).max(1024),at:W}).strict();N({outputTimings:M(Ss).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Cs.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Cs.extend({value:W}).optional()}).strict();let ws=e=>hs.refine(t=>Object.values(t).every(t=>t.length<=e)),Ts=N({composerIndicators:M(N({kind:z(`countdown`),id:D().min(1).max(64),expiresAtUnix:W,label:ws(256).optional(),tooltip:ws(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:W.optional(),cachedInputTokens:W.optional(),cacheWriteInputTokens:W.optional(),outputTokens:W.optional(),outputTokensPerSecond:bs.optional(),sessionOutputTokensPerSecond:bs.optional(),apiOutputTokensPerSecond:bs.optional(),reasoningOutputTokens:W.optional(),totalTokens:W.optional(),totalCostUsd:bs.optional(),totalCredits:bs.optional(),contextUsagePercent:bs.optional(),cacheHitRatePercent:xs.optional(),contextWindowTokens:W.optional(),contextUsedTokens:W.optional(),planFiveHourUsedPercent:xs.optional(),planFiveHourResetsAtUnix:W.optional(),planSevenDayUsedPercent:xs.optional(),planSevenDayResetsAtUnix:W.optional(),sessionCacheHitRatePercent:xs.optional(),timeToFirstOutputMs:W.optional(),latestRequestTimeToFirstOutputMs:W.optional(),costSource:R([`publicPrice`,`native`]).optional(),unpricedModels:M(D().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),Es=k().finite().min(0).max(100),Ds=R([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),Os=N({id:D().min(1).max(256),label:D().min(1).max(256),localizations:ms.optional()}).strict(),ks=N({product:D().min(1),periodType:Ds.optional(),scope:Os.optional(),localizations:ms.optional(),used:k().finite().nonnegative().optional(),limit:k().finite().nonnegative().optional(),unit:D().min(1).max(32).optional(),usagePercent:Es,resetsAt:D().min(1).optional()}).strict(),As=N({availableCount:k().int().safe().positive(),nextExpiresAt:D().min(1).optional(),expiresAt:M(D().min(1)).min(1).max(32).optional()}).strict(),js=N({used:k().finite().nonnegative().optional(),limit:k().finite().nonnegative().optional(),unit:D().min(1).max(32).optional(),label:D().min(1).optional(),scope:Os.optional(),localizations:ms.optional(),usedPercent:Es,resetsAt:D().min(1).optional(),periodType:Ds,productUsage:M(ks).min(1).optional(),resetCredits:As.optional()}).strict(),Ms=N({amount:k().finite().nonnegative(),currency:D().trim().min(1).max(8),label:D().trim().min(1).max(128).optional()}).strict();N({threadId:H,refresh:z(`exact`).optional()}).strict(),N({threadId:H,usage:Ts.nullable(),accountCredits:js.optional(),accountBalance:Ms.optional(),accountCreditsSupported:j().optional()}).strict();let Ns=D().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ps=D().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Fs=R([`priority`,`ultrafast`]),G=N({id:Ps,serviceTier:Fs.optional()}).strict();function Is(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let K=Ns.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Ls=Ns.max(256),Rs=N({id:K,label:Ns.max(256)}).strict(),zs=N({ref:G,label:Ns.max(256),resolvedModelLabel:Ls.optional(),fastModel:G.optional(),supportedThinkingOptionIds:M(K).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function Bs(e,t){if(t)return e?.models.find(e=>Is(e.ref,t)||Is(e.fastModel,t))}let Vs=M(Rs).superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Thinking option IDs must be unique`,path:[r,`id`]}),n.add(i.id)}),Hs=N({models:M(zs),defaultModel:G.optional(),thinkingOptions:Vs,defaultThinkingOptionId:K.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>Is(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>Is(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!Bs(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),Us=N({fork:j(),forkAcrossCwd:j(),rollbackLastTurn:j()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Ws=R([`live`,`atCreate`]),Gs=N({configuration:N({selectModel:j(),selectThinkingOption:j(),selectPermissionMode:j(),permissionModeScope:Ws.default(`live`)}).strict(),history:Us,subagents:N({observe:j(),readTranscript:j()}).strict().optional(),autonomousTurns:N({observe:j()}).strict().optional(),steer:j().optional(),persistentPlan:j().optional()}).strict();N({effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),availableThinkingOptions:Vs.optional(),effectivePermissionModeId:U.optional()}).strict().superRefine((e,t)=>{e.effectiveThinkingOptionId&&e.availableThinkingOptions&&!e.availableThinkingOptions.some(({id:t})=>t===e.effectiveThinkingOptionId)&&t.addIssue({code:`custom`,message:`Effective Thinking option must be currently available`,path:[`effectiveThinkingOptionId`]})});let Ks=N({open:z(!0)}).strict();F([N({status:z(`ready`),catalog:Hs,permissionModes:ys.optional(),capabilities:Gs,webUi:Ks.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),N({status:R([`notInstalled`,`unavailable`,`error`]),error:ds}).strict()]),N({harnessId:V,cwd:Ns.max(16384).optional(),refresh:j().optional(),purpose:z(`availability`).optional(),credentialAccess:R([`allow`,`retry`]).optional()}).strict(),N({harnessId:V}).strict(),N({}).strict(),N({threadId:H,model:G}).strict(),N({threadId:H,thinkingOptionId:K}).strict(),N({threadId:H,includeReferenceCapability:j().optional()}).strict(),I(`owner`,[N({owner:z(`codex`),locked:j(),effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),effectivePermissionModeId:U.optional(),history:Us.optional(),supportsThreadReferences:z(!0).optional()}).strict(),N({owner:z(`external`),harnessId:Ns.max(256),transportModelId:Ns.max(8192),effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),availableThinkingOptions:Vs.optional(),effectivePermissionModeId:U.optional(),catalog:Hs.optional(),history:Us,usage:Ts.optional(),locked:z(!0)}).strict()]),N({threadIds:M(H).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let qs=I(`owner`,[N({threadId:H,owner:z(`codex`)}).strict(),N({threadId:H,owner:z(`external`),harnessId:D().max(256).pipe(V)}).strict()]);N({threads:M(qs).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),N({threadId:H,text:D().optional()}).strict(),N({kind:z(`application`),value:D().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),xe}}).pipe(N({expectedTurnId:_s,clientUserMessageId:D().min(1),delivery:R([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),R([`activeTurn`,`newTurn`]),N({delivery:R([`official`,`activeTurn`,`newTurn`])}).strict();let Js=D().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),Ys=Js.pipe(V),Xs=Ys.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Zs=D().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),Qs=Xa().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),$s=N({en:D().max(4096),"zh-CN":D().max(4096).optional()}).strict(),ec=N({commands:M(N({terminal:D().max(256),command:D().max(4096)}).strict()).max(8),before:$s.optional(),after:$s.optional(),downloads:M(N({label:D().max(128),url:Qs}).strict()).max(8).optional()}).strict(),tc={id:Ys,name:D().trim().min(1).max(128),version:D().min(1).max(128),kind:z(`usage`).optional(),iconStyle:N({vector:N({viewBox:D().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:D().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:M(N({d:D().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:R([`evenodd`,`nonzero`]).optional(),fill:D().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:D().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:k().min(0).max(50).optional(),paddingRatio:k().min(0).max(.25).optional()}).strict().optional(),installation:ec.optional(),notice:$s.optional(),launchCommand:z(!0).optional(),links:N({website:Qs.optional(),documentation:Qs.optional(),installation:Qs.optional()}).strict().optional()};N({manifestVersion:z(1),...tc,adapterApiVersion:k().int().positive(),entry:Zs,icon:Zs.optional()}).strict();let nc=D().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),rc=N({...tc,icon:nc.optional()}).strict();N({}).strict(),N({plugins:M(rc.extend({id:Xs})).max(128)}).strict(),N({version:z(1),enabled:M(Ys).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let ic=Js,ac=R([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),oc=R([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),sc=D().trim().min(1).max(128);function cc(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let lc=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),uc=Zs.refine(e=>cc(e)!==void 0&&lc(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),dc=D().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Xa({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function fc(e){return P({en:e,"zh-CN":e})}let pc=fc(D().trim().min(1)),mc=M(oc).max(oc.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),hc=M(ac).max(ac.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),gc={key:D().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:pc,description:pc.optional()},_c={...gc,step:k().positive().optional(),default:k().optional()},vc=P({value:D(),label:pc}),yc=I(`type`,[P({...gc,type:z(`boolean`),default:j().optional()}),P({...gc,type:z(`string`),placeholder:pc.optional(),default:D().optional()}),P({..._c,type:z(`number`),min:k().optional(),max:k().optional()}),P({..._c,type:z(`range`),min:k(),max:k()}),P({...gc,type:z(`select`),options:M(vc).min(1),default:D().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),bc=N({manifestVersion:A().positive(),id:ic,name:F([sc,fc(sc)]),version:D().min(1).max(128),desktopApi:A().positive()}).passthrough().extend({manifestVersion:z(1),desktopApi:z(1),description:P({en:D().max(4096),"zh-CN":D().max(4096).optional()}).optional(),author:D().trim().min(1).max(128).optional(),repository:dc.optional(),details:P({en:D().max(16384),"zh-CN":D().max(16384).optional()}).optional(),icon:uc.optional(),screenshots:M(uc).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:P({script:Zs,style:Zs.optional()}).optional(),backend:P({script:Zs.refine(lc)}).optional(),slots:hc.default(()=>[]),settingsSchema:M(yc).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:mc.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),xc=D().regex(/^[a-f0-9]{64}$/u),Sc=P({state:R([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:xc.optional(),error:D().optional(),conflictWith:ic.optional()});P({controllerPid:A().positive(),targetId:D().nullable(),updatedAt:Sa(),handledReloadToken:Ja().optional(),extensions:L(D(),Sc),surfaces:L(D(),Sc).optional()});let Cc=R([`official`,`community`]);function wc(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Tc=dc.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||wc(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),Ec=P({id:ic,version:D().trim().min(1).max(128),name:pc.extend({en:sc,"zh-CN":sc}),description:fc(D().trim().min(1).max(4096)),details:fc(D().trim().min(1).max(16384)).optional(),author:D().trim().min(1).max(128),repository:dc,stars:k().int().min(0).optional(),downloads:k().int().min(0).optional(),categories:mc.optional(),trustTier:Cc.default(`community`),icon:dc.optional(),screenshots:M(dc).max(4).optional(),downloadUrl:Tc,sha256:xc,slots:hc.optional(),publishedAt:D().optional(),updatedAt:D().optional(),minCodexHostVersion:D().optional()});P({schemaVersion:z(1),generatedAt:D(),extensions:M(Ec).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Dc=D().trim().min(1).max(128),Oc=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,kc=ic.refine(e=>!Oc.test(e),`Reserved extension ID`),Ac=R([`desktop`,`web`]),jc=xc,Mc=Ja(),Nc=Zs.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Oc.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),Pc=bc.shape,Fc=(e,t=0)=>P({en:D().trim().min(t).max(e),"zh-CN":D().trim().min(t).max(e)}),Ic=e=>Nc.refine(t=>t.endsWith(e),`Expected a ${e} file`),Lc=Ic(`.mjs`),Rc=Ic(`.css`).optional(),zc=e=>e.normalize(`NFC`).toLowerCase(),Bc=P({manifestVersion:z(2),id:kc,name:Fc(128,1),version:D().trim().min(1).max(128),description:Fc(4096),details:Fc(16384).optional(),author:Pc.author,repository:Pc.repository,icon:Pc.icon.refine(e=>e===void 0||Nc.safeParse(e).success),screenshots:Pc.screenshots.refine(e=>e===void 0||e.every(e=>Nc.safeParse(e).success)),categories:Pc.categories,settingsSchema:Pc.settingsSchema,slots:Pc.slots.removeDefault().optional(),page:P({apiVersion:z(1),entry:Lc,style:Rc,title:Fc(128,1).optional()}).optional(),widget:P({apiVersion:z(1),entry:Lc,style:Rc}).optional(),desktop:P({apiVersion:z(1),script:Ic(`.js`),style:Rc}).optional(),web:P({apiVersion:z(1),entry:Lc.optional(),style:Rc}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:P({apiVersion:z(1),entry:Lc}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||zc(e)!==zc(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Vc({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let Hc=Dc,q=A().nonnegative(),Uc=P({revision:q,enabled:M(kc).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)}),{downloadUrl:Wc,...Gc}=Ec.shape,Kc=N({...Gc,id:kc,format:z(`codexhost`),targets:M(Ac).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:P({page:A().positive().optional(),widget:A().positive().optional(),desktop:A().positive().optional(),web:A().positive().optional(),backend:A().positive().optional()}),downloadUrl:Wc.refine(e=>e.startsWith(`https://`),`Expected HTTPS`)}).refine(({targets:e,apis:t})=>{let n=Vc({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);N({schemaVersion:z(2),generatedAt:D().min(1),extensions:M(Kc).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:dc,fetchedAt:Sa(),cached:j()});let qc={id:kc},Jc={...qc,activationId:Mc,digest:jc},Yc={...qc,activationId:Jc.activationId.optional()},Xc=D().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),Zc=D().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function Qc(e){return D().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let $c=P({type:z(`github`),repository:D().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Zc.optional(),tag:Zc.optional(),asset:D().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Nc.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),el=F([P({type:z(`catalog`),...qc}),$c,P({type:z(`zip`),base64:Qc(67108864).min(4)}),P({type:z(`zip`),localZipPath:Xc}),P({type:z(`localDir`),localDir:Xc})]),tl=I(`type`,[P({type:z(`catalog`),...qc}),$c,P({type:z(`zip`)}),P({type:z(`localDir`)})]),nl=P({...Jc,manifest:Bc,installedAt:Sa(),source:tl.optional()}),rl=e=>D().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),il={desktopConflictWith:kc.optional()},al=R([`none`,`inactive`,`starting`,`running`,`failed`]),ol=I(`state`,[nl.extend({state:z(`valid`),enabled:j(),...il,iconDataUrl:rl(131072).optional(),screenshotDataUrls:M(rl(524288)).max(4).optional(),backendState:al.optional(),backendError:D().optional()}),P({state:R([`invalid`,`incompatible`]),id:D().min(1),enabled:j(),error:D()})]);P({revision:q,configuration:Uc,diagnostics:M(D()),extensions:M(ol)}),P({revision:q,extensions:M(nl.extend({...il,settingsRevision:q})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`},sl=Object.freeze(Object.values(J));new Set(sl),P({});let cl={expectedRevision:q};P({...qc,...cl}),nl.extend({replaced:j()}),I(`state`,[P({state:z(`saved`),configuration:Uc}),P({state:z(`revision-conflict`),revision:q})]),P({...Yc,digest:Jc.digest.optional(),path:Nc}),P({mimeType:D().min(1),base64:Qc(16777216),digest:Jc.digest}),P({settingsRevision:q,values:us}),J.list,J.snapshot,J.catalog,P({forceRefresh:j().optional()}),J.install,P({source:el}),J.update,P({...qc,expectedDigest:Jc.digest,expectedActivationId:Jc.activationId.optional(),source:el.optional()}),J.enable,J.disable,J.uninstall,P({...qc,removeData:j().optional(),expectedDigest:Jc.digest.optional()}),P({...qc,removed:j()}),J.recover,P({expectedRevision:cl.expectedRevision.optional()}),J.asset,J.settingsGet,P(Yc),J.settingsSet,P({...Yc,expectedSettingsRevision:q,values:us}),J.backendInvoke,P({...Yc,method:Hc,params:B.optional()}),P({result:B}),N({threadId:H}).strict(),N({confirmed:j()}).strict(),[...sl],N({sections:M(N({id:D().min(1),name:D().min(1),threads:M(us)}).strict())}).strict(),N({threadId:D().min(1).max(1024),sectionId:D().min(1).max(1024).nullable()}).strict(),N({threadIds:M(D().min(1))}).strict(),N({threadId:D().min(1).max(1024),pinned:j()}).strict(),N({}).strict(),N({parents:L(D().min(1),D().min(1))}).strict(),N({prompt:D().max(16384).optional()}).strict(),N({projects:M(N({id:D(),name:D(),rootPaths:M(D())})),assignments:L(D(),D()),projectless:M(D()),pinned:M(D()),sectionProjects:L(D(),M(D())).optional()});let ll=L(D(),yo()),ul=N({epoch:D().uuid(),sequence:k().int().nonnegative()});I(`type`,[N({type:z(`skills-changed`),cursor:ul,cwd:D().optional()}),N({type:z(`harness-inspection-changed`),cursor:ul,harnessId:D().min(1)}),N({type:z(`display-settings-changed`),cursor:ul}),N({type:z(`preferences-changed`),cursor:ul,revision:k().int().nonnegative()}),N({type:z(`extensions-changed`),cursor:ul,revision:q}),N({type:z(`hello`),version:z(1),cursor:ul,reset:j()}),N({type:z(`changed`),cursor:ul,threadId:D().min(1),method:D().min(1)})]);let dl=I(`type`,[N({type:z(`text`),id:D(),prompt:D(),secret:j().optional(),optional:j().optional()}),N({type:z(`choice`),id:D(),prompt:D(),multiple:j(),allowOther:j(),optional:j().optional(),options:M(N({value:D(),label:D(),description:D().optional()}))})]),fl=I(`type`,[N({type:z(`approval`),title:D(),description:D().optional(),subject:yo().optional(),actions:M(N({id:D(),label:D(),effect:D()}))}),N({type:z(`question`),title:D().optional(),questions:M(dl)})]),pl=N({requestId:F([D(),k().int()]),threadId:D(),kind:R([`approval`,`question`]),interaction:fl,request:ll}),ml=N({id:D().min(1),clientUserMessageId:D().min(1),input:M(ll),presentationInput:M(ll).nullable().optional()}).passthrough();N({fields:M(N({path:M(F([D(),k().int().nonnegative()])),originalLength:k().int().nonnegative()}))});let hl=N({id:D().min(1),status:D().min(1),codexhostTurnOutcome:N({status:z(`unknown`),reason:D()}).optional(),items:M(N({id:D().min(1),type:D().min(1)}).passthrough()),codexhostFileOperations:M(N({beforeItemId:D().nullable(),item:N({id:D().min(1),type:D().min(1)}).passthrough()})).optional(),error:N({message:D().optional()}).passthrough().nullable().optional(),fingerprint:D().min(1).optional(),unchanged:z(!0).optional()}).passthrough(),gl=N({id:D().min(1).max(512),fingerprint:D().min(1).max(128)});N({threadId:D().min(1),knownTurns:M(gl).max(64).optional(),truncateToolOutput:j().optional()});let _l=N({harnessId:D().min(1),nativeSessionId:D().min(1)});N({cursor:ul,activeTurnId:D().min(1).nullable().optional(),command:N({name:D().min(1),turn:hl,subsequentTurnId:D().min(1).optional()}).optional(),thread:N({id:D().min(1),cwd:D(),modelProvider:D().min(1),createdAt:k(),updatedAt:k(),status:N({type:D()}).passthrough(),name:D().nullable().optional(),preview:D().optional(),codexhostImportSource:_l.optional(),turns:M(hl).length(0)}).passthrough(),turnsPage:N({data:M(hl).max(5),nextCursor:D().nullable()}),configuration:N({native:N({model:D().min(1).max(1024).optional(),reasoningEffort:D().min(1).max(128).optional()}).optional(),effectiveModel:G.optional(),effectiveThinkingOptionId:K.optional(),effectivePermissionModeId:U.optional()}),queue:N({items:M(ml),pausedReason:R([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:M(pl)}),N({version:z(1),owner:z(`service`).optional(),pid:k().int().positive(),port:k().int().min(1).max(65535),token:D().regex(/^[0-9a-f]{64}$/u),startedAt:k(),epoch:D().uuid()}),N({epoch:D().uuid(),threadId:D().min(1),requestId:F([D(),k().int()]),result:ll}),N({includeArchived:j().optional(),officialCursor:N({live:D().nullable(),archived:D().nullable().optional()}).strict().optional(),scope:N({cwd:D().min(1).max(4096),excludeCwds:M(D().min(1).max(4096)).max(1024)}).strict().optional()}).strict(),N({threads:M(us),ownership:M(qs),archivedThreadIds:M(H),officialCursor:N({live:D().nullable(),archived:D().nullable().optional()}).strict().optional()}).strict();let vl=R([`running`,`waiting`,`idle`,`unknown`]),yl=P({harnessId:V,title:D().optional(),status:vl,archived:j()}),bl=P({revision:A().nonnegative(),parents:L(H,H),nodes:L(H,yl),truncated:j()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,nodes:t})=>Object.entries(e).every(([e,n])=>Object.hasOwn(t,e)&&Object.hasOwn(t,n)),`Missing Thread tree node`),xl=D().min(1).max(128);P({});let Sl=P({subscriptionId:xl});P({}),Sl.extend({snapshot:bl});let Cl=D().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);N({available:j()}).strict(),N({path:D().min(1),mimeType:Cl}).strict();let wl=R([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);I(`ok`,[N({ok:z(!0),text:D()}).strict(),N({ok:z(!1),error:N({code:wl}).strict()}).strict()]),N({threadId:H.optional(),cwd:D().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Tl=N({name:D().min(1).regex(/^[^\s[\]]+$/u),description:D().optional(),path:D().min(1),scope:R([`project`,`global`]),source:D().min(1)}).strict();N({revision:k().int().nonnegative(),complete:j(),skills:M(Tl),warnings:M(D()).optional()}).strict(),N({cwd:D().min(1).optional()}).strict();let El=N({kind:R([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:D().min(1)}).strict(),Dl=I(`status`,[N({status:z(`not-installed`)}),N({status:z(`not-running`)}),N({status:z(`not-logged-in`)}),N({status:z(`https-disabled`)}),N({status:z(`not-serving`),command:D()}),N({status:z(`occupied`),target:D()}),N({status:z(`serving`),url:D(),funnel:j()}),N({status:z(`error`),message:D()})]);N({state:Dl,error:D().optional()}).strict();let Ol=I(`status`,[N({status:z(`on`)}),N({status:z(`off`)}),N({status:z(`invalid`),reason:D()})]),kl=N({lan:j(),autostart:Ol}).strict(),Al=N({expiresAt:D().optional(),issuing:j(),failure:N({detail:D().optional(),retryAt:D(),paused:j()}).optional()}),jl=I(`status`,[N({status:z(`off`),reason:R([`invite`,`name-taken`,`banned`]).optional()}),N({status:z(`connecting`),reason:R([`full`,`unreachable`]).optional()}),N({status:z(`connected`),url:D(),certificate:Al}),N({status:z(`missing-certificate`),url:D(),certificate:Al}),N({status:z(`stopped`),reason:R([`replaced`,`rejected`,`unsupported-version`])})]);D().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),D().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let Ml=R([`official`,`self-hosted`]);N({secret:D().min(1),lastUsedAt:k().nullable(),networkUrls:M(El),directCandidates:M(El).optional(),tailscale:Dl,background:kl.optional(),relay:N({state:jl,enabled:j(),kind:Ml,officialHost:D(),customHost:D().optional(),officialHostname:D().optional(),customHostname:D().optional(),quotaUntil:D().optional()}).strict().optional()}).strict();let Nl=P({threadId:D().min(1).max(1024),view:R([`result`,`messages`]),from:k().int().min(1).max(2**53-1).optional(),to:k().int().min(1).max(2**53-1).optional()}),Pl=N({id:D().min(1).max(256),harnessId:D().min(1),label:D().min(1).max(512),provider:R([`openai-codex`,`xai`])}).strict(),Fl=D().regex(/^[a-z][a-z0-9-]{0,47}$/),Il=N({name:Fl,source:Pl,importedAt:D()}).strict(),Ll=I(`action`,[N({action:z(`list`)}).strict(),N({action:z(`import`),sourceId:D().min(1).max(256),name:Fl,confirmed:z(!0)}).strict(),N({action:z(`reimport`),sourceId:D().min(1).max(256),name:Fl,confirmed:z(!0)}).strict(),N({action:z(`remove`),name:Fl,confirmed:z(!0)}).strict()]),Rl=N({provider:D().min(1).max(128),type:R([`oauth`,`api_key`,`unknown`]),label:D().min(1).max(512).optional(),vendor:R([`openai-codex`,`xai`]).optional()}).strict();N({sources:M(Pl),targets:M(N({harnessId:D(),providers:M(R([`openai-codex`,`xai`])),imports:M(Il),others:M(Rl).default([])}).strict())}).strict(),N({targetHarnessId:D().min(1).max(128).optional(),request:Ll}).strict(),N({events:j()});let zl=M(P({agent:D().min(1).max(128),section:R([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);P({entries:zl.nullable()}),P({}),P({entries:zl,initializeOnly:j().optional()});let Bl=P({enabled:j(),timeoutMinutes:k().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let Vl=D().regex(/^external$/u),Hl=V.transform(e=>String(e)),Ul=P({model:G.optional(),thinkingOptionId:K.optional(),permissionModeId:U.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),Wl=P({lastHarness:V.optional(),byHarness:L(Hl,Ul)}),Gl=P({model:G.optional(),thinkingOptionId:K.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Kl=P({byHarness:L(Hl,Gl)}),ql=D().min(1).max(1024),Jl=P({idleRelease:Bl.optional(),favorites:L(Hl,M(ql).max(2048)).default({}),newThread:Wl.optional(),delegation:Kl.optional()});P({scope:Vl,revision:k().int().nonnegative(),values:Jl}),P({scope:Vl.default(`external`)});let Yl=I(`kind`,[P({kind:z(`idleRelease`),value:Bl}),P({kind:z(`favorite`),harnessId:V,modelId:ql,enabled:j()}),P({kind:z(`favorites`),harnessId:V,modelIds:M(ql).max(2048)}),P({kind:z(`newThread`),lastHarness:V.optional(),harnessId:V.optional(),configuration:Ul.optional()}),P({kind:z(`delegation`),harnessId:V,configuration:Gl.nullable()})]);P({scope:Vl.default(`external`),operations:M(Yl).min(1).max(256),initializeOnly:j().optional(),expectedRevision:k().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),P({version:z(1),revision:k().int().nonnegative(),scopes:L(Vl,Jl)});let Xl=k().finite().nonnegative(),Zl=P({input:Xl,output:Xl,cacheRead:Xl.optional(),cacheWrite:Xl.optional(),cacheWrite1h:Xl.optional()}),Ql=D().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);P({path:D(),entries:M(P({key:D(),price:Zl})),error:D().nullable()}),P({}),P({key:Ql,price:Zl.nullable(),previousKey:Ql.optional()}),P({model:Ql});let $l=P({official:j().optional(),canonicalModelId:D().min(1).optional(),provider:D().min(1).max(512),model:D().min(1).max(512),price:Zl});P({price:Zl.nullable(),suggestions:M($l).max(6).optional()});let eu=[`today`,`7d`,`30d`,`90d`,`all`],Y=k().int().min(0).max(2**53-1),tu=D().regex(/^\d{4}-\d{2}-\d{2}$/u),nu=D().min(1).max(128),ru=D().min(1).max(512),iu=D().min(1).max(4096);P({range:R(eu),timeZone:D().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:nu.optional(),model:ru.nullable().optional(),project:iu.nullable().optional(),date:tu.optional()});let au=P({requests:Y,inputTokens:Y,cachedInputTokens:Y,cacheWriteInputTokens:Y,cacheKnownInputTokens:Y,cacheHitCachedInputTokens:Y,cacheHitInputTokens:Y,outputTokens:Y,reasoningOutputTokens:Y,costUsd:k().finite().min(0),unpricedRequests:Y,unmeteredRequests:Y}),ou=au.shape,su=P({harness:nu,sessionId:D().min(1).max(512),project:iu.nullable(),title:D().min(1).max(200).optional(),models:M(ru).max(16),firstAtMs:Y,lastAtMs:Y,...ou});P({range:R(eu),from:tu.nullable(),to:tu,filters:P({harness:nu.nullable(),model:ru.nullable(),unknownModel:j(),project:iu.nullable(),unknownProject:j(),date:tu.nullable()}),reading:P({complete:j(),sources:Y,read:Y}),failures:M(P({harness:nu,message:D().max(2048)})).max(256),options:P({harnesses:M(nu).max(256),models:M(ru.nullable()).max(4096),projects:M(iu.nullable()).max(4096)}),modelLabels:M(P({harness:nu,model:ru,label:ru})).max(4096).optional(),credits:M(P({harness:nu,model:ru.nullable(),credits:k().finite().min(0),reportedRequests:Y,requests:Y})).max(4096).optional(),totals:au,daily:M(P({date:tu,harness:nu,...ou})).max(2e5),hourly:M(P({weekday:k().int().min(0).max(6),hour:k().int().min(0).max(23),...ou})).max(168),byHarness:M(P({harness:nu,...ou})).max(256),byModel:M(P({model:ru.nullable(),...ou,harnessPricedRequests:Y})).max(4096),byProject:M(P({project:iu.nullable(),...ou})).max(4096),sessions:M(su).max(100),recentSessions:M(su).max(100).optional()}),N({threadId:H}),N({discarded:j()});let cu=I(`type`,[N({id:D().min(1),type:z(`choice`),prompt:D(),options:M(N({value:D().min(1),label:D(),description:D().optional()})).min(1),multiple:j(),allowOther:j(),optional:j()}),N({id:D().min(1),type:z(`text`),prompt:D(),multiline:j(),secret:z(!1),optional:j(),placeholder:D().optional(),prefill:D().optional()})]),lu=N({interactionId:D().min(1),turnId:D().min(1),title:D().optional(),questions:M(cu).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});P({threadId:D().min(1)}),N({questions:M(lu)}),P({threadId:D().min(1),turnId:D().min(1),interactionId:D().min(1),answers:L(D(),M(D())),cancelled:j().default(!1)}),N({accepted:z(!0)});let uu=`codexhostActiveTurnId`,du=/* @__PURE__ */ new Set([uu,`codexhostTurnChanges`,`codexhostToolOutput`]),fu=N({path:D(),oldText:D().nullable(),newText:D()});N({sessionId:D().min(1),turn:k().int().nonnegative(),path:D().min(1).optional()}),N({diffs:M(fu)}),P({}),P({}),N({reference:N({sessionId:D().min(1),epoch:D().min(1),turn:k().int().nonnegative(),seq:k().int().nonnegative(),callId:D().min(1),part:k().int().nonnegative(),version:D().min(1)}),length:k().int().nonnegative(),bytes:k().int().nonnegative()}),P({title:D().trim().min(1).max(200),type:R([`info`,`warning`,`danger`]),body:D().trim().min(1).max(16384)}),P({}),P({url:D().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status`.split(`.`));let pu=R([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),mu=R([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);P({threadId:D(),title:D(),harnessId:D(),state:pu,reason:mu,inactiveMs:k().nonnegative()}),P({threadId:H,turnId:_s});let hu=N({email:D().trim().min(1).max(320).optional(),label:D().trim().min(1).max(256).optional(),plan:D().trim().min(1).max(128).optional(),credits:js.optional(),balance:Ms.optional()}).strict();function gu(e){return e.refine(e=>{let t=e;return t.credits!==void 0||t.balance!==void 0},{message:`Account must report either credits or a balance`})}let _u=gu(hu),vu={harnessId:V,harnessName:D().trim().min(1).max(128)},yu=N(vu).strict();N({}).strict(),N({sources:M(yu).max(128)}).strict(),N({harnessId:V,refresh:j().optional()}).strict(),N({...vu,account:_u.nullable(),accounts:M(_u).max(8).optional()}).strict(),N({refresh:j().optional()}).strict(),N({accounts:M(gu(hu.extend(vu))).max(128)}).strict(),N({harnessId:Xs,model:G.optional(),thinkingOptionId:K.optional(),permissionModeId:U.optional(),prewarm:z(!0).optional()}).strict();let bu=D().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);N({harnessId:Xs}).strict().extend({path:bu.nullable()}),N({path:bu.nullable(),restartRequired:j()}).strict(),N({harnessId:V,action:R([`check`,`update`,`install`]),confirmedVersion:D().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let xu=N({currentVersion:D().min(1).max(128),latestVersion:D().min(1).max(128),updateAvailable:j(),canUpdate:j(),latestVerifiedVersion:D().min(1).max(128).optional(),confirmationRequired:z(!0).optional(),versionKind:R([`cli`,`application`]).optional(),manualUpdateUrl:Xa().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:D().max(2048).optional(),messageCode:D().min(1).max(128).optional(),notice:hs.optional(),latestVersionKind:R([`unknown`,`tracking-branch`]).optional()}).strict();N({taskId:D().uuid()}).strict(),I(`status`,[N({taskId:D().uuid(),status:z(`running`)}).strict(),N({taskId:D().uuid(),status:z(`succeeded`),result:xu}).strict(),N({taskId:D().uuid(),status:z(`failed`),error:N({code:k().int(),message:D().min(1).max(2048)}).strict()}).strict()]);let Su=D().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Cu=D().trim().min(1),wu=R([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),Tu=N({accountId:Su,label:Cu.max(256),email:D().email().max(320).optional(),planType:wu.optional()}).strict(),Eu=R([`ready`,`unavailable`]);N({version:z(2),currentAccountId:Su.nullable(),phase:Eu,revision:k().int().nonnegative(),instanceId:Cu.max(1024).optional(),accounts:M(Tu).max(1)}).strict(),N({accountId:Su,refresh:j().optional()}).strict(),N({accountId:Su,usage:Ts.nullable(),accountCredits:js.optional(),freshness:R([`live`,`cached`]),observedAt:D().datetime().nullable()}).strict();let Du=1e3,Ou=D().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),ku=Ou.max(1024),Au=N({nativeSessionId:ku,title:Ou.max(4096).nullable(),updatedAt:k().int().nonnegative().max(864e13),cwd:Ou.max(16384),running:j().nullable()}).strict();N({}).strict(),N({harnesses:M(N({harnessId:Xs,name:Ou.max(128)}).strict()).max(128)}).strict(),N({harnessId:Xs,query:D().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:k().int().nonnegative().safe().optional(),limit:k().int().min(1).max(Du).optional()}).strict(),N({candidates:M(Au).max(Du),total:k().int().nonnegative().safe()}).strict(),N({harnessId:Xs,nativeSessionId:ku}).strict(),N({threadId:Ou.max(1024).pipe(H)}).strict();let ju=D().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Mu=ku,Nu=Au;N({}).strict(),N({candidates:M(Nu).max(1e3)}).strict(),N({nativeSessionId:Mu}).strict(),N({threadId:ju.max(1024).pipe(H)}).strict(),N({threadId:H,lastTurnId:_s}).strict(),N({threadId:H}).strict();let Pu=D().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();N({commands:M(N({id:Pu,invocation:D().min(1).max(128),label:D().trim().min(1).max(128),description:D().trim().min(1).max(512).optional(),localizations:ms.optional(),argumentMode:R([`none`,`text`]),kind:R([`command`,`skill`]).optional()}).strict()),warnings:M(D().min(1)).optional(),source:R([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),N({harnessId:V,cwd:D().min(1).optional()}).strict(),N({threadId:H}).strict(),N({threadId:H,commandId:Pu,turnId:_s.optional(),arguments:us.optional()}).strict(),N({accepted:z(!0),turnId:_s.optional()}).strict();let Fu=z(`2.0`).optional(),X=xo().optional(),Iu=D().min(1),Lu=F([D(),k().int()]),Ru=N({code:k().int(),message:D(),data:B.optional()}).catchall(B).superRefine(as([`data`]));F([N({jsonrpc:Fu,id:Lu,method:Iu,params:B.optional(),result:X,error:X}).catchall(B).superRefine(as([`jsonrpc`,`params`,`result`,`error`])),N({jsonrpc:Fu,id:X,method:Iu,params:B.optional(),result:X,error:X}).catchall(B).superRefine(as([`jsonrpc`,`id`,`params`,`result`,`error`])),N({jsonrpc:Fu,id:Lu,method:X,params:X,result:B,error:X}).catchall(B).superRefine(as([`jsonrpc`,`method`,`params`,`error`])),N({jsonrpc:Fu,id:Lu,method:X,params:X,result:X,error:Ru}).catchall(B).superRefine(as([`jsonrpc`,`method`,`params`,`result`]))]);let zu=D().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});P({harnessId:V,nativeSessionId:zu,locator:B.optional(),formatVersion:z(1)}).superRefine(as([`locator`])),P({harnessId:V,nativeSessionId:zu,nativeTurnKey:zu,formatVersion:z(1)}),P({harnessId:V,nativeSessionId:zu,checkpointId:zu,locator:B.optional(),formatVersion:z(1)}).superRefine(as([`locator`]));let Bu=D().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Vu=R([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Hu=P({version:Bu,installation:Vu,phase:R([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:k().int().nonnegative(),downloadedBytes:k().int().nonnegative().optional(),totalBytes:k().int().positive().optional(),error:D().min(1).max(500).nullable(),serviceStopOutput:D().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});P({});let Uu=D().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`);P({currentVersion:Bu,installation:Vu.nullable(),latestVersion:Bu.nullable(),updateAvailable:j(),installationAvailable:j(),releaseNotes:D().min(1).max(2e4).nullable(),releaseNotesUrl:Uu.nullable(),status:Hu.nullable(),error:D().min(1).max(500).nullable()}),P({status:Hu}),P({status:Hu.nullable()});let Wu=P({icon:D().min(1).max(16).optional(),title:D().min(1).max(120),body:D().min(1).max(1200),contributors:M(D().min(1).max(39)).max(30)}),Gu=P({summary:D().min(1).max(600).optional(),themes:M(Wu).min(1).max(12)}),Ku=P({version:Bu,publishedAt:Sa(),url:D().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Gu.nullable(),en:Gu.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});P({manual:j().optional()}),P({announcement:Ku.nullable(),unread:j()}),P({version:Bu}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let qu=R([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);N({runningVersion:D().nullable(),installedVersion:D().nullable(),restartRequired:j(),remote:j(),updateSupported:j(),update:N({phase:qu,targetVersion:D().nullable(),error:D().nullable()})});let Ju=N({version:D().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();N({hostname:D().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable(),action:R([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:j().optional(),version:D().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),N({state:R([`installed`,`not-installed`])}).strict();let Z=D().min(1).max(1024),Yu={hostId:Z.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},Q={...Yu,threadId:Z},Xu=D().min(1).max(8e3),Zu={text:Xu,requestId:Z};I(`accepted`,[N({accepted:z(!0),startQueuedItemId:Z.optional()}),N({accepted:z(!1),code:R([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:D()})]),I(`available`,[N({available:z(!1)}),N({available:z(!0),items:M(N({id:Z,clientUserMessageId:Z,preview:D().max(801)})).max(100)})]);let Qu=I(`kind`,[P({kind:z(`hosts`)}),P({kind:z(`create`),...Yu,cwd:D().min(1).max(8192),epoch:Z}),P({kind:z(`projectHarnesses`),...Yu,epoch:Z}),P({kind:z(`inspectHarness`),...Yu,epoch:Z,cwd:D().min(1).max(8192),harnessId:Z}),P({kind:z(`startSelected`),...Yu,epoch:Z,cwd:D().min(1).max(8192),harnessId:Z,model:D().min(1).max(4096),serviceTier:R([`priority`,`ultrafast`]).optional(),reasoningEffort:Z.optional()}),P({kind:z(`status`),...Q}),P({kind:z(`list`),...Yu,cursor:D().nullable(),archived:j(),includeLoaded:z(!0).optional()}),P({kind:z(`read`),...Q,page:P({cursor:D().min(1).max(8192).nullable(),epoch:Z.optional(),sortDirection:R([`asc`,`desc`]).optional(),limit:k().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),P({kind:z(`usage`),...Q,epoch:Z}),P({kind:z(`configure`),...Q,epoch:Z,modelId:Z.optional(),serviceTier:Fs.optional(),thinkingOptionId:Z.optional(),permissionModeId:Z.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),P({kind:z(`prompt`),...Q,epoch:Z,text:Xu,requestId:Z.optional()}),P({kind:z(`queue`),...Q,epoch:Z}),P({kind:z(`delivery`),...Q,epoch:Z,action:I(`kind`,[P({kind:z(`enqueue`),...Zu}),P({kind:z(`steer`),...Zu,turnId:Z}),P({kind:z(`remove`),itemId:Z}),P({kind:z(`start`),itemId:Z,onlyIfHead:z(!0).optional()})])}),P({kind:z(`interrupt`),...Q,epoch:Z,turnId:Z}),P({kind:z(`rename`),...Q,epoch:Z,name:D().min(1).max(512)}),P({kind:z(`archive`),...Q,epoch:Z,archived:j()}),P({kind:z(`respond`),...Q,epoch:Z,requestId:F([Z,k().int()]),result:L(D(),yo())})]),$u=D().min(1).max(1024),ed=N({hostId:$u,displayName:D().min(1).max(1024),source:R([`codex-managed`,`discovered`]),sshAlias:D().max(1024).nullable(),sshHost:D().min(1).max(1024),sshPort:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable(),autoConnect:j(),connectionAnalyticsId:D().max(1024).optional()}),td=P({displayName:D().min(1).max(1024),hostname:D().min(1).max(1024),sshPort:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable()});I(`action`,[P({action:z(`session`),operation:Qu}),P({action:z(`list`)}),P({action:z(`catalog`)}),P({action:z(`read-thread`),hostId:$u.refine(e=>e!==`local`),input:Nl}),P({action:z(`save`),draft:td,previous:ed.nullable()}),P({action:z(`remove`),previous:ed}),P({action:z(`connect`),hostId:$u,enabled:j()}),P({action:z(`state`),hostId:$u}),P({action:z(`runtime`),hostId:$u}),P({action:z(`update`),hostId:$u.refine(e=>e!==`local`),version:Ju.shape.version})]),F([P({result:B}),P({error:P({code:k().int(),message:D()})})]),P({prompt:D().trim().min(1).max(2e3),cwd:D().max(4096).nullable()}),D().trim().min(1).max(60).nullable();let nd=D().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),rd=F([D(),N({en:D()}).catchall(D())]),id=N({title:rd.optional(),description:rd.optional(),icon:D().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:D().optional()});N({extensions:M(N({id:nd,name:D().min(1).max(214),version:D().min(1).max(128),format:z(`dsh`),supportedTargets:ko([z(`web`)]),enabledTargets:M(z(`web`)).max(1),source:D().min(1).max(4096),projectUrl:D().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:D(),meta:id.optional(),loadError:D().optional()})),loadedIds:M(nd),safeMode:j(),storeError:D().optional()});let ad=D().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);N({spec:D().trim().min(1).max(4096),registry:ad.optional()}).strict(),N({id:nd,enabled:j()}).strict(),N({id:nd}).strict();let $=D().regex(/^[a-zA-Z0-9_-]{1,64}$/u),od=D().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),sd=R([`relay`,`tailscale`,`lan`,`custom`]),cd=R([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]);N({peers:M(N({peerId:$,hostId:od,name:D().min(1).max(120),origin:D().min(1).max(2048),transportKind:sd,encrypted:j(),enabled:j(),state:cd,latencyMs:k().int().nonnegative().optional(),version:D().max(128).optional(),platform:D().max(64).optional(),hostname:D().max(255).optional(),homeDir:D().max(4096).optional(),lastError:D().max(1e3).optional(),projectCount:k().int().nonnegative(),createdAt:D(),updatedAt:D()}))}),N({connectionUrl:D().min(1).max(4096).optional(),origin:D().min(1).max(2048).optional(),token:D().min(1).max(2048).optional(),name:D().trim().min(1).max(120).optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),N({peerId:$,name:D().trim().min(1).max(120).optional(),connectionUrl:D().min(1).max(4096).optional(),origin:D().min(1).max(2048).optional(),token:D().min(1).max(2048).optional(),enabled:j().optional()}),N({peerId:$}),N({removed:j()}),N({peerId:$.optional(),connectionUrl:D().min(1).max(4096).optional(),origin:D().min(1).max(2048).optional(),token:D().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`),N({ok:j(),latencyMs:k().int().nonnegative().optional(),origin:D().max(2048).optional(),transportKind:sd.optional(),encrypted:j().optional(),version:D().max(128).optional(),platform:D().max(64).optional(),hostname:D().max(255).optional(),homeDir:D().max(4096).optional(),projectCount:k().int().nonnegative().optional(),error:D().max(1e3).optional()});let ld=N({id:D().min(1).max(1024),name:D().min(1).max(512),path:D().min(1).max(8192),threadIds:M(D().min(1).max(1024))}),ud=N({version:D().max(128),platform:D().max(64),hostname:D().max(255),homeDir:D().max(4096).optional(),epoch:D().min(1).max(256),projects:M(ld)}),dd=N({name:D().min(1).max(512),path:D().min(1).max(8192),kind:z(`directory`)});N({peerId:$,path:D().min(1).max(8192).optional()}),N({path:D().min(1).max(8192),parentPath:D().min(1).max(8192).nullable(),homeDir:D().min(1).max(8192).optional(),entries:M(dd)}),N({peerId:$,parentPath:D().min(1).max(8192),name:D().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),N({path:D().min(1).max(8192),name:D().min(1).max(255)}),N({peerId:$,path:D().min(1).max(8192),title:D().trim().min(1).max(255).optional()}),N({peerId:$,workspaceId:D().min(1).max(1024),title:D().trim().min(1).max(255)}),N({peerId:$,workspaceId:D().min(1).max(1024)}),N({workspaceId:D().min(1).max(1024).optional(),manifest:ud}),z(1);function fd(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
|
|
123
123
|
/* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
|
|
124
|
-
if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];
|
|
125
|
-
|
|
126
|
-
if(e===void 0)
|
|
127
|
-
`,r:`\r`,t:` `},sd=/[\\\u0000-\u001f]/u;function cd(e){return e===` `||e===`
|
|
128
|
-
`||e===`\r`||e===` `}function ld(e){return e>=`0`&&e<=`9`||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}(class e{static EMPTY=e.fromObject({});static fromText(t){let n=new e;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new e;return n.object=typeof t==`object`&&t&&!Array.isArray(t)?t:{},n.sealed=!0,n}chunks=[];object;sealed=!1;#e=[];#t=0;#n=0;#r=`root`;#i=!1;#a=0;#o=!1;#s=``;#c=null;#l=[];#u=!1;#d;#f=!1;#p=/* @__PURE__ */ new Map;#m=[];#h=/* @__PURE__ */ new Map;get isSealed(){return this.sealed}get invalid(){return this.scan(),this.#r===`invalid`||this.#f}append(e){if(this.sealed)throw Error(`PartialArguments: cannot append to a sealed view`);e.length!==0&&(this.chunks.push(e),this.#t+=e.length,this.#e.push(this.#t))}settle(t){if(this.object!==void 0||t.length!==this.#t)return e.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return e.fromText(t);n+=r.length}return this.chunks=t.length===0?[]:[t],this.#e=t.length===0?[]:[t.length],this.sealed=!0,this}refresh(){if(this.#h.size===0)return!1;this.scan();let e=!1,t=!1;for(let n of this.#h.values())n.completion?t=!0:e=this.refreshRead(n)||e;if(t)for(let t of this.#h.values())t.completion&&(e=this.refreshRead(t)||e);return this.sealed&&this.#h.clear(),e}refreshRead(e){let t=e.answer();return!Object.is(t,e.last)&&(e.last=t,!0)}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),e=>e.length)}has(e){return this.remember(`has`,e,()=>this.hasNow(e))}complete(e){return this.remember(`complete`,e,()=>this.completeNow(e))}stringLength(e,t){let n=Math.max(1,Math.floor(t?.step??1)),r=t?.offset??0;return this.remember(`length:${n}:${r}`,e,()=>this.lengthNow(e),e=>e===void 0?void 0:Math.ceil((e+r)/n))}stringExceeds(e,t){let n=Math.max(0,Math.floor(t));return this.remember(`exceeds:${n}`,e,()=>(this.lengthNow(e,n+1)??0)>n)}text(e){return this.remember(`text`,e,()=>this.textNow(e))}textPrefix(e,t){let n=Math.max(1,Math.floor(t));return this.remember(`prefix:${n}`,e,()=>this.textPrefixNow(e,n))}value(e){return this.remember(`value`,e,()=>this.valueNow(e))}remember(e,t,n,r){this.scan();let i=n();if(!this.sealed){let a=`${e}/${t}`;this.#h.has(a)||this.#h.set(a,{completion:e===`complete`,answer:r===void 0?n:()=>r(n()),last:r===void 0?i:r(i)})}return i}closedNow(){return this.sealed||this.#r===`closed`||this.#r===`invalid`}keysNow(){return this.object===void 0?this.#m:Object.keys(this.object)}hasNow(e){return this.object===void 0?this.#p.has(e):Object.hasOwn(this.object,e)}completeNow(e){if(this.object!==void 0)return Object.hasOwn(this.object,e);let t=this.#p.get(e);return t!==void 0&&t.end>=0&&(t.kind===`string`?t.invalidAt===void 0:!t.invalid)}lengthNow(e,t=1/0){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t.length:void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;if(n.text!==void 0&&n.text.at===n.end)return n.text.length;let r=n.length??={at:n.start,length:0,text:``};return this.readString(n,r,t,!1),r.length}textNow(e){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t:void 0}let t=this.#p.get(e);if(t?.kind!==`string`)return;if(t.text===void 0&&t.end>=0&&t.needsDecoding&&t.invalidAt===void 0){let e;try{e=JSON.parse(`"${this.slice(t.start,t.end)}"`)}catch{}e!==void 0&&(t.text={at:t.end,length:e.length,text:e})}let n=t.text??={at:t.start,length:0,text:``};return this.readString(t,n,1/0,!0),n.text}textPrefixNow(e,t){if(this.object!==void 0){let n=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof n==`string`?n.slice(0,t):void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;let r=n.prefixes??=/* @__PURE__ */ new Map,i=r.get(t);return i===void 0&&(i={at:n.start,length:0,text:``},r.set(t,i)),this.readString(n,i,t,!0),i.text}valueNow(e){if(this.object!==void 0){if(!Object.hasOwn(this.object,e))return;let t=this.object[e];return typeof t==`string`?void 0:t}let t=this.#p.get(e);if(!(t?.kind!==`value`||t.end<0||t.invalid)){if(t.parsed===void 0)try{t.parsed=JSON.parse(this.slice(t.start,t.end))}catch{t.invalid=!0,this.#f=!0}return t.parsed}}chunkAt(e){let t=0,n=this.#e.length;for(;t<n;){let r=t+n>>>1;this.#e[r]<=e?t=r+1:n=r}return t}slice(e,t){if(e>=t)return``;let n=this.chunkAt(e),r=this.chunkAt(t-1),i=n===0?0:this.#e[n-1];if(n===r)return this.chunks[n].slice(e-i,t-i);let a=[this.chunks[n].slice(e-i)];for(let e=n+1;e<r;e++)a.push(this.chunks[e]);return a.push(this.chunks[r].slice(0,t-this.#e[r-1])),a.join(``)}readString(e,t,n,r){let i=Math.min(e.end<0?this.#n:e.end,e.invalidAt??1/0,this.#d??1/0);if(!e.needsDecoding){let e=Math.min(i-t.at,n-t.length);if(e<=0)return;r&&(t.text+=this.slice(t.at,t.at+e)),t.at+=e,t.length+=e;return}let a=this.chunkAt(t.at);for(;t.at<i&&t.length<n;){let o=a===0?0:this.#e[a-1],s=this.chunks[a],c=s.slice(t.at-o,Math.min(s.length,i-o)),l=c.search(sd),u=Math.min(l<0?c.length:l,n-t.length);if(u>0){r&&(t.text+=c.slice(0,u)),t.at+=u,t.length+=u,t.at===o+s.length&&a++;continue}let d=c.length>1?c[1]:t.at+1<i?this.chunks[a+1][0]:void 0,f,p=2;if(c[0]===`\\`&&d===void 0&&e.end<0)return;if(c[0]===`\\`&&d===`u`){let n=this.slice(t.at+2,Math.min(i,t.at+6)),r=!0;for(let e=0;e<n.length;e++)ld(n[e])||(r=!1);if(r){if(n.length<4&&e.end<0)return;n.length===4&&(f=String.fromCharCode(Number.parseInt(n,16)))}p=6}else c[0]===`\\`&&d!==void 0&&(f=od[d]);if(f===void 0){e.invalidAt=t.at,this.#f=!0;return}for(r&&(t.text+=f),t.length++,t.at+=p;a<this.chunks.length&&t.at>=this.#e[a];)a++}}scan(){if(this.object===void 0&&this.#n!==this.#t)for(let e=this.chunkAt(this.#n);e<this.chunks.length&&this.#d===void 0;e++){let t=this.chunks[e],n=e===0?0:this.#e[e-1];for(let e=this.#n-n;e<t.length&&this.#r!==`invalid`;e++){if(this.#r===`string`||this.#r===`nested`&&this.#u){let n=this.stringBoundary(t,e);if(this.#n+=n-e,e=n,e===t.length)break}this.step(t[e],this.#n),this.#n++}}}stringBoundary(e,t){let n=t;for(;;){let t=e.indexOf(`"`,n),r=t<0?e.length:t;if(this.#r===`string`){let t=this.#c;!t.needsDecoding&&sd.test(e.slice(n,r))&&(t.needsDecoding=!0)}let i=r;for(;i>n&&e[i-1]===`\\`;)i--;let a=(r-i)%2==1!==(i===n&&this.#i);if(this.#i=t<0&&a,t<0||!a)return r;n=t+1}}step(e,t){switch(this.#r){case`root`:if(cd(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(cd(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(cd(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(cd(e))return;if(e===`:`){this.#r=`value`;return}this.fail();return;case`value`:this.beginValue(e,t);return;case`string`:{let e=this.#c;e.end=t,this.#c=null,this.#r=`comma-or-end`;return}case`scalar`:this.stepScalar(e,t);return;case`nested`:this.stepNested(e,t);return;case`comma-or-end`:if(cd(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(cd(e))return;this.fail();return;
|
|
124
|
+
if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let pd={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
|
|
125
|
+
`,r:`\r`,t:` `},md=/[\\\u0000-\u001f]/u;function hd(e){return e===` `||e===`
|
|
126
|
+
`||e===`\r`||e===` `}function gd(e){return e>=`0`&&e<=`9`||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}(class e{static EMPTY=e.fromObject({});static fromText(t){let n=new e;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new e;return n.object=typeof t==`object`&&t&&!Array.isArray(t)?t:{},n.sealed=!0,n}chunks=[];object;sealed=!1;#e=[];#t=0;#n=0;#r=`root`;#i=!1;#a=0;#o=!1;#s=``;#c=null;#l=[];#u=!1;#d;#f=!1;#p=/* @__PURE__ */ new Map;#m=[];#h=/* @__PURE__ */ new Map;get isSealed(){return this.sealed}get invalid(){return this.scan(),this.#r===`invalid`||this.#f}append(e){if(this.sealed)throw Error(`PartialArguments: cannot append to a sealed view`);e.length!==0&&(this.chunks.push(e),this.#t+=e.length,this.#e.push(this.#t))}settle(t){if(this.object!==void 0||t.length!==this.#t)return e.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return e.fromText(t);n+=r.length}return this.chunks=t.length===0?[]:[t],this.#e=t.length===0?[]:[t.length],this.sealed=!0,this}refresh(){if(this.#h.size===0)return!1;this.scan();let e=!1,t=!1;for(let n of this.#h.values())n.completion?t=!0:e=this.refreshRead(n)||e;if(t)for(let t of this.#h.values())t.completion&&(e=this.refreshRead(t)||e);return this.sealed&&this.#h.clear(),e}refreshRead(e){let t=e.answer();return!Object.is(t,e.last)&&(e.last=t,!0)}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),e=>e.length)}has(e){return this.remember(`has`,e,()=>this.hasNow(e))}complete(e){return this.remember(`complete`,e,()=>this.completeNow(e))}stringLength(e,t){let n=Math.max(1,Math.floor(t?.step??1)),r=t?.offset??0;return this.remember(`length:${n}:${r}`,e,()=>this.lengthNow(e),e=>e===void 0?void 0:Math.ceil((e+r)/n))}stringExceeds(e,t){let n=Math.max(0,Math.floor(t));return this.remember(`exceeds:${n}`,e,()=>(this.lengthNow(e,n+1)??0)>n)}text(e){return this.remember(`text`,e,()=>this.textNow(e))}textPrefix(e,t){let n=Math.max(1,Math.floor(t));return this.remember(`prefix:${n}`,e,()=>this.textPrefixNow(e,n))}value(e){return this.remember(`value`,e,()=>this.valueNow(e))}remember(e,t,n,r){this.scan();let i=n();if(!this.sealed){let a=`${e}/${t}`;this.#h.has(a)||this.#h.set(a,{completion:e===`complete`,answer:r===void 0?n:()=>r(n()),last:r===void 0?i:r(i)})}return i}closedNow(){return this.sealed||this.#r===`closed`||this.#r===`invalid`}keysNow(){return this.object===void 0?this.#m:Object.keys(this.object)}hasNow(e){return this.object===void 0?this.#p.has(e):Object.hasOwn(this.object,e)}completeNow(e){if(this.object!==void 0)return Object.hasOwn(this.object,e);let t=this.#p.get(e);return t!==void 0&&t.end>=0&&(t.kind===`string`?t.invalidAt===void 0:!t.invalid)}lengthNow(e,t=1/0){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t.length:void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;if(n.text!==void 0&&n.text.at===n.end)return n.text.length;let r=n.length??={at:n.start,length:0,text:``};return this.readString(n,r,t,!1),r.length}textNow(e){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t:void 0}let t=this.#p.get(e);if(t?.kind!==`string`)return;if(t.text===void 0&&t.end>=0&&t.needsDecoding&&t.invalidAt===void 0){let e;try{e=JSON.parse(`"${this.slice(t.start,t.end)}"`)}catch{}e!==void 0&&(t.text={at:t.end,length:e.length,text:e})}let n=t.text??={at:t.start,length:0,text:``};return this.readString(t,n,1/0,!0),n.text}textPrefixNow(e,t){if(this.object!==void 0){let n=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof n==`string`?n.slice(0,t):void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;let r=n.prefixes??=/* @__PURE__ */ new Map,i=r.get(t);return i===void 0&&(i={at:n.start,length:0,text:``},r.set(t,i)),this.readString(n,i,t,!0),i.text}valueNow(e){if(this.object!==void 0){if(!Object.hasOwn(this.object,e))return;let t=this.object[e];return typeof t==`string`?void 0:t}let t=this.#p.get(e);if(!(t?.kind!==`value`||t.end<0||t.invalid)){if(t.parsed===void 0)try{t.parsed=JSON.parse(this.slice(t.start,t.end))}catch{t.invalid=!0,this.#f=!0}return t.parsed}}chunkAt(e){let t=0,n=this.#e.length;for(;t<n;){let r=t+n>>>1;this.#e[r]<=e?t=r+1:n=r}return t}slice(e,t){if(e>=t)return``;let n=this.chunkAt(e),r=this.chunkAt(t-1),i=n===0?0:this.#e[n-1];if(n===r)return this.chunks[n].slice(e-i,t-i);let a=[this.chunks[n].slice(e-i)];for(let e=n+1;e<r;e++)a.push(this.chunks[e]);return a.push(this.chunks[r].slice(0,t-this.#e[r-1])),a.join(``)}readString(e,t,n,r){let i=Math.min(e.end<0?this.#n:e.end,e.invalidAt??1/0,this.#d??1/0);if(!e.needsDecoding){let e=Math.min(i-t.at,n-t.length);if(e<=0)return;r&&(t.text+=this.slice(t.at,t.at+e)),t.at+=e,t.length+=e;return}let a=this.chunkAt(t.at);for(;t.at<i&&t.length<n;){let o=a===0?0:this.#e[a-1],s=this.chunks[a],c=s.slice(t.at-o,Math.min(s.length,i-o)),l=c.search(md),u=Math.min(l<0?c.length:l,n-t.length);if(u>0){r&&(t.text+=c.slice(0,u)),t.at+=u,t.length+=u,t.at===o+s.length&&a++;continue}let d=c.length>1?c[1]:t.at+1<i?this.chunks[a+1][0]:void 0,f,p=2;if(c[0]===`\\`&&d===void 0&&e.end<0)return;if(c[0]===`\\`&&d===`u`){let n=this.slice(t.at+2,Math.min(i,t.at+6)),r=!0;for(let e=0;e<n.length;e++)gd(n[e])||(r=!1);if(r){if(n.length<4&&e.end<0)return;n.length===4&&(f=String.fromCharCode(Number.parseInt(n,16)))}p=6}else c[0]===`\\`&&d!==void 0&&(f=pd[d]);if(f===void 0){e.invalidAt=t.at,this.#f=!0;return}for(r&&(t.text+=f),t.length++,t.at+=p;a<this.chunks.length&&t.at>=this.#e[a];)a++}}scan(){if(this.object===void 0&&this.#n!==this.#t)for(let e=this.chunkAt(this.#n);e<this.chunks.length&&this.#d===void 0;e++){let t=this.chunks[e],n=e===0?0:this.#e[e-1];for(let e=this.#n-n;e<t.length&&this.#r!==`invalid`;e++){if(this.#r===`string`||this.#r===`nested`&&this.#u){let n=this.stringBoundary(t,e);if(this.#n+=n-e,e=n,e===t.length)break}this.step(t[e],this.#n),this.#n++}}}stringBoundary(e,t){let n=t;for(;;){let t=e.indexOf(`"`,n),r=t<0?e.length:t;if(this.#r===`string`){let t=this.#c;!t.needsDecoding&&md.test(e.slice(n,r))&&(t.needsDecoding=!0)}let i=r;for(;i>n&&e[i-1]===`\\`;)i--;let a=(r-i)%2==1!==(i===n&&this.#i);if(this.#i=t<0&&a,t<0||!a)return r;n=t+1}}step(e,t){switch(this.#r){case`root`:if(hd(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(hd(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(hd(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(hd(e))return;if(e===`:`){this.#r=`value`;return}this.fail();return;case`value`:this.beginValue(e,t);return;case`string`:{let e=this.#c;e.end=t,this.#c=null,this.#r=`comma-or-end`;return}case`scalar`:this.stepScalar(e,t);return;case`nested`:this.stepNested(e,t);return;case`comma-or-end`:if(hd(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(hd(e))return;this.fail();return;
|
|
129
127
|
/* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
|
|
130
128
|
case`invalid`:return;
|
|
131
129
|
/* v8 ignore next 2 -- Every scanner mode has a handler above. */
|
|
132
|
-
default:
|
|
130
|
+
default:_d(this.#r)}}fail(){this.#d=this.#n,this.#r=`invalid`,this.#c=null}beginKey(e){this.#r=`key`,this.#a=e+1,this.#o=!1,this.#i=!1}stepKey(e,t){if(e<` `){this.fail();return}if(this.#i){this.#i=!1;return}if(e===`\\`){this.#i=!0,this.#o=!0;return}if(e!==`"`)return;let n=this.slice(this.#a,t);if(this.#o)try{this.#s=JSON.parse(`"${n}"`)}catch{this.fail();return}else this.#s=n;this.#r=`colon`}open(e){this.#p.has(this.#s)||this.#m.push(this.#s),this.#p.set(this.#s,e),this.#c=e}beginValue(e,t){hd(e)||(e===`"`?(this.open({kind:`string`,start:t+1,end:-1,needsDecoding:!1,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0}),this.#i=!1,this.#r=`string`):e===`}`||e===`,`||e===`:`||e===`]`?this.fail():(this.open({kind:`value`,start:t,end:-1,parsed:void 0,invalid:!1}),e===`{`||e===`[`?(this.#r=`nested`,this.#l=[e===`{`?`}`:`]`],this.#u=!1,this.#i=!1):this.#r=`scalar`))}stepScalar(e,t){(e===`,`||e===`}`||hd(e))&&(this.closeValue(t),this.#r=e===`,`?`key-only`:e===`}`?`closed`:`comma-or-end`)}stepNested(e,t){if(this.#u)this.#u=!1;else if(e===`"`)this.#u=!0;else if(e===`{`||e===`[`)this.#l.push(e===`{`?`}`:`]`);else if(e===`}`||e===`]`){if(this.#l.pop()!==e){this.fail();return}this.#l.length===0&&(this.closeValue(t+1),this.#r=`comma-or-end`)}}closeValue(e){let t=this.#c;t.end=e,this.#c=null}});function _d(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function vd(e,t){let n=Object.getOwnPropertyDescriptor(e,`constructor`)?.value;if(typeof n!=`function`)return!1;try{return n.name===t&&n.prototype===e&&Function.prototype.toString.call(n)===Function.prototype.toString.call(t===`Array`?Array:Object)}catch{return!1}}function yd(e){return Object.getPrototypeOf(e)===null&&vd(e,`Object`)}function bd(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!vd(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&yd(n)}function xd(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&yd(t)}function Sd(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function Cd(e,t){let n=/* @__PURE__ */ new Set,r,i=(e,t)=>{e!==void 0&&(e.kind===`root`?r=t:e.kind===`array`?e.target[e.index]=t:Object.defineProperty(e.target,e.key,{value:t,enumerable:!0,configurable:!0,writable:!0}))},a=[{kind:`visit`,value:e,...t?{destination:{kind:`root`}}:{}}];for(let e=a.pop();e!==void 0;e=a.pop()){if(e.kind===`leave`){n.delete(e.source);continue}if(e.kind===`array-item`){if(!Object.prototype.hasOwnProperty.call(e.source,e.index))return;a.push({kind:`visit`,value:e.source[e.index],...e.target===void 0?{}:{destination:{kind:`array`,target:e.target,index:e.index}}});continue}if(e.kind===`object-property`){a.push({kind:`visit`,value:e.source[e.key],...e.target===void 0?{}:{destination:{kind:`object`,target:e.target,key:e.key}}});continue}let r=e.value;if(r===null){i(e.destination,null);continue}if(typeof r==`boolean`||typeof r==`string`){i(e.destination,r);continue}if(typeof r==`number`){if(!Number.isFinite(r)||Object.is(r,-0))return;i(e.destination,r);continue}if(typeof r!=`object`||n.has(r))return;if(Array.isArray(r)){if(!bd(r))return;let o=r.length;if(Reflect.ownKeys(r).length!==o+1)return;let s=t?[]:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o-1;e>=0;e--)a.push({kind:`array-item`,source:r,index:e,...s===void 0?{}:{target:s}});continue}if(!xd(r))return;let o=Sd(r);if(o===void 0)return;let s=t?{}:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o.length-1;e>=0;e--){let t=o[e];
|
|
133
131
|
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
134
|
-
if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function
|
|
132
|
+
if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function wd(e){return Cd(e,!0)}function Td(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
|
|
135
133
|
/* v8 ignore next -- the loop condition guarantees one pending task. */
|
|
136
134
|
if(e===void 0)continue;if(e.kind===`property`){n.push({kind:`visit`,node:e.source[e.key]});continue}let r=e.node;if(typeof r!=`object`||!r||r instanceof AbortSignal||t.has(r))continue;t.add(r),Object.freeze(r);let i=Object.keys(r);for(let e=i.length-1;e>=0;e--){let t=i[e];
|
|
137
135
|
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
138
|
-
t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function yd(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.sessionId,n);let n=/* @__PURE__ */ new Map,r=[];for(let i of e)if(i.parentSessionId!==void 0&&t.has(i.parentSessionId)){let e=n.get(i.parentSessionId)??[];e.push(i),n.set(i.parentSessionId,e)}else r.push(i);let i=[],a=/* @__PURE__ */ new Set,o=(e,t)=>{if(a.has(e.sessionId)){console.warn(`[session-controller] lineage cycle at ${e.sessionId}; emitting as root`);return}a.add(e.sessionId);let{agentAvailable:r,...s}=e;i.push({...s,depth:t});let c=n.get(e.sessionId);if(c!==void 0)for(let e of c)o(e,t+1)};for(let e of r)o(e,0);for(let t of e)a.has(t.sessionId)||o(t,0);return i}var bd=class{rebuild;listeners=/* @__PURE__ */ new Set;dirty=!1;notifyPending=!1;scheduled=`none`;scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!==`microtask`&&this.schedule(`microtask`)}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled===`none`&&this.schedule(typeof globalThis.requestAnimationFrame==`function`?`frame`:`microtask`)}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}},xd=class{rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;anyNotifier=new bd(()=>{});faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){let r=this.rows.get(e);r?.kind===`sequenced`&&n<=r.seq||(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e))}applyLive(e,t,n){let r=this.rows.get(e);r?.kind===`sequenced`&&n<r.seq||(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e))}applyCached(e){for(let t of Object.keys(e))this.rows.get(t)?.kind!==`sequenced`&&(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t))}seed(e,t,n){for(let[e,t]of this.rows)t.kind===`cached`&&(this.rows.delete(e),this.changed(e));let r=e.values;for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new bd(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},Sd=class{readRemote;values;pending=/* @__PURE__ */ new Map;constructor(e,t){this.readRemote=e,this.values=new Map(t)}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.values.set(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}};function Cd(){let e=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=Array.from(e,(e,t)=>(t===6?e&15|64:t===8?e&63|128:e).toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function wd(e){return{kind:`leaf`,entries:e,length:e.length}}function Td(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Ed(e){if(e.kind===`leaf`)return e.entries;let t=Array(e.length),n=[e],r=0;for(;n.length>0;){let e=n.pop();if(e.kind===`concat`)n.push(e.right,e.left);else for(let n of e.entries)t[r]=n,r+=1}return t}function Dd(e,t,n,r){let i;return{get entries(){return i??=Ed(e),i},hasMore:t,revision:n,change:r}}var Od=class{listeners=/* @__PURE__ */ new Set;window=wd([]);snapshot=Dd(this.window,!1,0,{kind:`replace`,entries:[]});getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=wd(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Td(wd(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Td(this.window,wd(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Ed(this.window).filter(t=>t.type!==`transient`||t.event.data.attemptId!==e);if(t!==void 0){let e=n.findIndex(e=>e.event.seq>t.event.seq);e<0?n.push(t):n.splice(e,0,t)}this.window=wd(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Dd(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function kd(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Ad(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function jd(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`${t} index must be a non-negative safe integer`);return e}function Md(e){let t=_d(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Nd(e){let t=[];for(let n of e){let e=Pd(n);if(e.type===`chunk`){t.push({time:e.time,chunk:e.chunk});continue}let r=e.type===`tool-call-chunks`?e.args:e.texts,i=e.time0;for(let n=0;n<r.length;n+=1){n>0&&(i+=e.dt[n-1]);let a;a=e.type===`text-chunks`?{type:`text-delta`,index:e.index,text:r[n]}:e.type===`reasoning-chunks`?{type:`reasoning-delta`,index:e.index,text:r[n]}:{type:`tool-call-delta`,index:e.index,id:e.id,...Object.hasOwn(e,`name`)?{name:e.name}:{},argumentsDelta:r[n]},t.push({time:i,chunk:a})}}return t}function Pd(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Assistant stream record must be an object`);let t=e;switch(t.type){case`text-chunks`:case`reasoning-chunks`:{Ld(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Id(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Fd(t,e.length,t.type),t}case`tool-call-chunks`:{Ld(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Id(t.args,`tool-call-chunks args`);if(e.length===0)throw TypeError(`tool-call-chunks args must be non-empty`);if(typeof t.id!=`string`||t.id.length===0)throw TypeError(`tool-call-chunks id must be a non-empty string`);if(t.name!==void 0&&(typeof t.name!=`string`||t.name.length===0))throw TypeError(`tool-call-chunks name must be a non-empty string`);return Fd(t,e.length,t.type),t}case`chunk`:{Ld(t,[`type`,`time`,`chunk`],`chunk`);let e=Ad(t.time);if(typeof t.chunk!=`object`||t.chunk===null||Array.isArray(t.chunk))throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let n;try{n=Md(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return vd({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Fd(e,t,n){if(Ad(e.time0),jd(e.index,n),!Array.isArray(e.dt)||e.dt.some(e=>!Number.isSafeInteger(e)))throw TypeError(`${n} dt must contain safe integers`);if(e.dt.length!==t-1)throw TypeError(`${n} dt length must be one less than its members`);let r=e.time0;for(let t of e.dt)if(r+=t,!Number.isSafeInteger(r))throw TypeError(`${n} member times must stay safe integers`)}function Id(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Ld(e,t,n){if(Object.keys(e).length!==t.length||!t.every(t=>Object.hasOwn(e,t)))throw TypeError(`${n} Assistant stream record must contain exactly ${t.join(`, `)}`)}var Rd=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Nd(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=zd(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function zd(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Bd(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Vd={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},Hd={...Vd,turnWindow:{...Vd.turnWindow,minMessages:200}};var Ud=class{sessionId;remote;baseSeq=ee(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new Rd;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Od;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Sd(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new xd,n.cachedView){let e=n.cachedView;this.cachedJournal=e.journal,this.baseSeq=e.baseSeq,this.hasMore=e.hasMore,this.lastSyncedAt=e.lastSyncedAt,this.projections.applyCached(e.projections),this.eventSource.replace(e.entries,e.hasMore)}this.address=n.address,this.parentAvailable=n.parentAvailable,this.notifier=new bd(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){let t=Cd(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}activeTurnForSteering(){let e=this.projections.get(lu);return typeof e==`string`?e:null}async prompt(e,t,n,r){let i=r??Cd();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=kd(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:kd()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}return!s.ok&&s.error.code===`remote/outcome-unknown`&&this.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(this.acceptPrompt(),s):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:s.error,requestId:i},this.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i)}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Vd})}catch(e){t===this.openGeneration&&(this.olderError=(0,i.isRemoteFailure)(e)?e:new o(`gateway/internal`,`Could not load earlier history.`,{}))}finally{t===this.openGeneration&&(this.loadingOlder=!1,this.notifier.markDirty())}}loadThrough(e){if(this.openState!==`open`||!this.hasMore||this.baseSeq<=e)return Promise.resolve();if(this.jumpPromise!==null)return this.jumpTargetSeq=p(Math.min(this.jumpTargetSeq??e,e)),this.jumpPromise;if(this.loadingOlder)return Promise.resolve();let t=this.events;if(t===void 0)return Promise.resolve();let n={beforeSeq:this.baseSeq,hasMore:this.hasMore,pages:[]};this.pendingHistory=n,this.jumpTargetSeq=e,this.olderError=null,this.loadingOlder=!0,this.notifier.markDirty();let r=this.openGeneration;return this.jumpPromise=(async()=>{try{for(;n.hasMore&&this.jumpTargetSeq!==null&&n.beforeSeq>this.jumpTargetSeq;){if(r!==this.openGeneration)return;let e=n.beforeSeq;if(await t.prepend({beforeSeq:e,...Hd}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=ee(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:this.toolOutputs.values,entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(uu),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Vd),e!==this.openGeneration||this.events!==n)return;this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:Bd(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=ee(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,uu),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:ee(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:ee(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:Gd(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=Gd(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,Gd(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,Wd(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){let n=this.submissionSettlements.get(e);
|
|
136
|
+
t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function Ed(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.sessionId,n);let n=/* @__PURE__ */ new Map,r=[];for(let i of e)if(i.parentSessionId!==void 0&&t.has(i.parentSessionId)){let e=n.get(i.parentSessionId)??[];e.push(i),n.set(i.parentSessionId,e)}else r.push(i);let i=[],a=/* @__PURE__ */ new Set,o=(e,t)=>{if(a.has(e.sessionId)){console.warn(`[session-controller] lineage cycle at ${e.sessionId}; emitting as root`);return}a.add(e.sessionId);let{agentAvailable:r,...s}=e;i.push({...s,depth:t});let c=n.get(e.sessionId);if(c!==void 0)for(let e of c)o(e,t+1)};for(let e of r)o(e,0);for(let t of e)a.has(t.sessionId)||o(t,0);return i}var Dd=class{rebuild;listeners=/* @__PURE__ */ new Set;dirty=!1;notifyPending=!1;scheduled=`none`;scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!==`microtask`&&this.schedule(`microtask`)}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled===`none`&&this.schedule(typeof globalThis.requestAnimationFrame==`function`?`frame`:`microtask`)}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}},Od=class{rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;anyNotifier=new Dd(()=>{});faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){let r=this.rows.get(e);r?.kind===`sequenced`&&n<=r.seq||(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e))}applyLive(e,t,n){let r=this.rows.get(e);r?.kind===`sequenced`&&n<r.seq||(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e))}applyCached(e){for(let t of Object.keys(e))this.rows.get(t)?.kind!==`sequenced`&&(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t))}seed(e,t,n){for(let[e,t]of this.rows)t.kind===`cached`&&(this.rows.delete(e),this.changed(e));let r=e.values;for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new Dd(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},kd=class{readRemote;values;pending=/* @__PURE__ */ new Map;constructor(e,t){this.readRemote=e,this.values=new Map(t)}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.values.set(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}};function Ad(){let e=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=Array.from(e,(e,t)=>(t===6?e&15|64:t===8?e&63|128:e).toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function jd(e){return{kind:`leaf`,entries:e,length:e.length}}function Md(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Nd(e){if(e.kind===`leaf`)return e.entries;let t=Array(e.length),n=[e],r=0;for(;n.length>0;){let e=n.pop();if(e.kind===`concat`)n.push(e.right,e.left);else for(let n of e.entries)t[r]=n,r+=1}return t}function Pd(e,t,n,r){let i;return{get entries(){return i??=Nd(e),i},hasMore:t,revision:n,change:r}}var Fd=class{listeners=/* @__PURE__ */ new Set;window=jd([]);snapshot=Pd(this.window,!1,0,{kind:`replace`,entries:[]});getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=jd(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Md(jd(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Md(this.window,jd(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Nd(this.window).filter(t=>t.type!==`transient`||t.event.data.attemptId!==e);if(t!==void 0){let e=n.findIndex(e=>e.event.seq>t.event.seq);e<0?n.push(t):n.splice(e,0,t)}this.window=jd(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Pd(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Id(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Ld(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Rd(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`${t} index must be a non-negative safe integer`);return e}function zd(e){let t=wd(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Bd(e){let t=[];for(let n of e){let e=Vd(n);if(e.type===`chunk`){t.push({time:e.time,chunk:e.chunk});continue}let r=e.type===`tool-call-chunks`?e.args:e.texts,i=e.time0;for(let n=0;n<r.length;n+=1){n>0&&(i+=e.dt[n-1]);let a;a=e.type===`text-chunks`?{type:`text-delta`,index:e.index,text:r[n]}:e.type===`reasoning-chunks`?{type:`reasoning-delta`,index:e.index,text:r[n]}:{type:`tool-call-delta`,index:e.index,id:e.id,...Object.hasOwn(e,`name`)?{name:e.name}:{},argumentsDelta:r[n]},t.push({time:i,chunk:a})}}return t}function Vd(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Assistant stream record must be an object`);let t=e;switch(t.type){case`text-chunks`:case`reasoning-chunks`:{Wd(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Ud(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Hd(t,e.length,t.type),t}case`tool-call-chunks`:{Wd(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Ud(t.args,`tool-call-chunks args`);if(e.length===0)throw TypeError(`tool-call-chunks args must be non-empty`);if(typeof t.id!=`string`||t.id.length===0)throw TypeError(`tool-call-chunks id must be a non-empty string`);if(t.name!==void 0&&(typeof t.name!=`string`||t.name.length===0))throw TypeError(`tool-call-chunks name must be a non-empty string`);return Hd(t,e.length,t.type),t}case`chunk`:{Wd(t,[`type`,`time`,`chunk`],`chunk`);let e=Ld(t.time);if(typeof t.chunk!=`object`||t.chunk===null||Array.isArray(t.chunk))throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let n;try{n=zd(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Td({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Hd(e,t,n){if(Ld(e.time0),Rd(e.index,n),!Array.isArray(e.dt)||e.dt.some(e=>!Number.isSafeInteger(e)))throw TypeError(`${n} dt must contain safe integers`);if(e.dt.length!==t-1)throw TypeError(`${n} dt length must be one less than its members`);let r=e.time0;for(let t of e.dt)if(r+=t,!Number.isSafeInteger(r))throw TypeError(`${n} member times must stay safe integers`)}function Ud(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Wd(e,t,n){if(Object.keys(e).length!==t.length||!t.every(t=>Object.hasOwn(e,t)))throw TypeError(`${n} Assistant stream record must contain exactly ${t.join(`, `)}`)}var Gd=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Bd(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=Kd(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function Kd(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function qd(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Jd={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},Yd={...Jd,turnWindow:{...Jd.turnWindow,minMessages:200}};var Xd=class{sessionId;remote;baseSeq=ee(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new Gd;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Fd;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new kd(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Od,n.cachedView){let e=n.cachedView;this.cachedJournal=e.journal,this.baseSeq=e.baseSeq,this.hasMore=e.hasMore,this.lastSyncedAt=e.lastSyncedAt,this.projections.applyCached(e.projections),this.eventSource.replace(e.entries,e.hasMore)}this.address=n.address,this.parentAvailable=n.parentAvailable,this.notifier=new Dd(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){let t=Ad(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}activeTurnForSteering(){let e=this.projections.get(uu);return typeof e==`string`?e:null}async prompt(e,t,n,r){let i=r??Ad();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=Id(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Id()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}return!s.ok&&s.error.code===`remote/outcome-unknown`&&this.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(this.acceptPrompt(),s):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:s.error,requestId:i},this.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i)}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Jd})}catch(e){t===this.openGeneration&&(this.olderError=(0,i.isRemoteFailure)(e)?e:new o(`gateway/internal`,`Could not load earlier history.`,{}))}finally{t===this.openGeneration&&(this.loadingOlder=!1,this.notifier.markDirty())}}loadThrough(e){if(this.openState!==`open`||!this.hasMore||this.baseSeq<=e)return Promise.resolve();if(this.jumpPromise!==null)return this.jumpTargetSeq=p(Math.min(this.jumpTargetSeq??e,e)),this.jumpPromise;if(this.loadingOlder)return Promise.resolve();let t=this.events;if(t===void 0)return Promise.resolve();let n={beforeSeq:this.baseSeq,hasMore:this.hasMore,pages:[]};this.pendingHistory=n,this.jumpTargetSeq=e,this.olderError=null,this.loadingOlder=!0,this.notifier.markDirty();let r=this.openGeneration;return this.jumpPromise=(async()=>{try{for(;n.hasMore&&this.jumpTargetSeq!==null&&n.beforeSeq>this.jumpTargetSeq;){if(r!==this.openGeneration)return;let e=n.beforeSeq;if(await t.prepend({beforeSeq:e,...Yd}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=ee(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:this.toolOutputs.values,entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(du),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Jd),e!==this.openGeneration||this.events!==n)return;this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:qd(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=ee(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,du),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:ee(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:ee(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:Qd(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=Qd(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,Qd(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,Zd(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){let n=this.submissionSettlements.get(e);
|
|
139
137
|
/* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
|
|
140
|
-
n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function Wd(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function Gd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;(e.type===`image`||e.type===`file`)&&typeof e.attachment==`object`&&e.attachment!==null&&t.push(e.attachment)}return t}var Kd=class{views=/* @__PURE__ */ new Map;take(e){let t=this.views.get(e);return this.views.delete(e),t}remember(e,t){if(this.views.delete(e),this.views.set(e,t),this.views.size<=8)return;let n=this.views.keys().next().value;return this.views.delete(n),n}delete(e){this.views.delete(e)}clear(){this.views.clear()}};function qd(e){return e===-1?-1:p(e)}let Jd=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]);var Yd=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new Kd;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];notifier=new bd(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r){let t=this.recentViews.remember(e,r);t&&this.projectionStores.get(t)?.discard(uu)}return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.listMutations=null,this.listInflight=null,this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new Ud(e,this.remote,{...t===void 0?{}:{address:t,...n===void 0?{}:{parentAvailable:n}},onEngaged:e=>{!this.disposed&&this.retainedIds(this.summaries).has(e.sessionId)&&(this.engagedSessions.has(e.sessionId)||(this.engagedSessions.add(e.sessionId),this.recordMutation({kind:`engaged`,sessionId:e.sessionId})),this.sessions.get(e.sessionId)?.handleBlank(!1))},projections:this.projectionStore(e),cachedView:this.recentViews.take(e)})}effectiveBlank(e){return e.blank&&!this.engagedSessions.has(e.sessionId)}retainedIds(e){let t=new Set(e.map(e=>e.sessionId));for(let e of this.sessions.keys())t.add(e);for(let e of this.addresses.keys())t.add(e);return t}pruneEngagement(e,t){t.has(e)||this.engagedSessions.delete(e)}projectionStore(e){let t=this.projectionStores.get(e);if(t===void 0){t=new xd;let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.values();this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.values()===a&&r.clear():r.seed({...t.value,asOfSeq:qd(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(){return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve()}refreshList(e){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let t=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0;let n=this.summaries,r=[];return this.listMutations=r,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:t,...e?{cursor:e}:{}});if(this.listMutations!==r)return;if(i.ok){let a=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...n.filter(e=>!o.has(e.sessionId)&&(s||!t&&a.has(e.sessionId)))],l=this.listPhase===`pending`?c:ad(n,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of r)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=r.reduce(Xd,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===r&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==r)return;this.listState=`error`,this.listError=e}finally{this.listMutations===r&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=Zd(r.error);e!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:e,updatedAt:Date.now(),running:!1,blank:!0}})}return r}async fork(e){let t=this.sessions.get(e.sessionId);if(t&&t.getSnapshot().openState!==`open`)return{ok:!1,error:new o(`session/syncing`,`Wait for the Session history to finish synchronizing.`,{})};let n=this.summaries.find(t=>t.sessionId===e.sessionId),r=await this.remote.session.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:e.atSeq}}),i=r.ok?r.value.sessionId:Zd(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq)),n}mergeSummary(e){this.recordMutation({kind:`upsert`,summary:e}),this.updateParentAvailability()}recordMutation(e){this.disposed||(this.listMutations?.push(e),this.summaries=Xd(this.summaries,e),this.notifier.markDirty())}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):(this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq)),this.notifier.markDirty())}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=qd(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,uu)}this.notifier.markDirty()}handleSessionAdded(e,t=!0){t&&this.summaryOnlyIds.delete(e.sessionId),this.mergeSummary(e),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let n=this.sessions.get(e.sessionId);n?.handleRestored(),n?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=qd(t.asOfSeq);for(let[r,i]of Object.entries(t.values))n.apply(r,i,e);return}case`cached`:n.applyCached(t.values);return;default:ud(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){this.summaryOnlyIds.delete(e);let t=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`);this.recordMutation(t?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e}),t?this.sessions.get(e)?.handleRunning(!1):(this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved());let n=this.projectionStores.get(e)?.values().subagentCatalog;!t&&(n===void 0||n.length===0)&&this.projectionStores.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e),this.projectionLoads.delete(e);for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e),this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0}),this.updateParentAvailability(),this.sessions.get(e)?.handleRunning(t)}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t})}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(Jd);this.listMutations=null,this.listInflight=null,this.nextCursor=void 0,this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=yd(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);return e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e),{items:this.itemsCache,hasMore:!!this.nextCursor,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([e,t])=>[e,{values:t.values(),state:`idle`,error:null,...this.projectionLoads.get(e)}]))}}};function Xd(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.find(e=>e.sessionId===t.summary.sessionId);if(n===void 0)return[t.summary,...e];let r={...n,blank:n.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...n.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...n.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...n.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};return r.cwd===n.cwd&&r.parentSessionId===n.parentSessionId&&r.origin===n.origin&&r.blank===n.blank&&r.agentAvailable===n.agentAvailable&&r.running===n.running?[...e]:e.map(e=>e.sessionId===t.summary.sessionId?r:e)}case`remove`:return e.filter(e=>e.sessionId!==t.sessionId);case`status`:return e.map(e=>e.sessionId===t.sessionId&&(e.running!==t.running||e.agentAvailable!==t.agentAvailable||t.running&&e.blank)?{...e,running:t.running,agentAvailable:t.agentAvailable,blank:e.blank&&!t.running}:e);case`activity`:return e.map(e=>e.sessionId===t.sessionId&&t.updatedAt>e.updatedAt?{...e,updatedAt:t.updatedAt}:e);case`engaged`:return e.map(e=>e.sessionId===t.sessionId&&e.blank?{...e,blank:!1}:e)}}function Zd(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var Qd=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},$d=class extends Error{rpcError;sourceSessionId;name=`SessionForkError`;constructor(e,t){super(`session fork failed: ${e.code}: ${e.message}`),this.rpcError=e,this.sourceSessionId=t}};function ef(e,t,n){if(e!==void 0)return e;if(t!==void 0&&t!==``){let e=me(t);if(e!==``)return e}return n}function tf(e){let t=/^(.*?)\((\d+)\)$/u.exec(e);if(t?.[1]!==void 0&&t[2]!==void 0)return`${t[1]}(${BigInt(t[2])+1n})`;let n=/^(.*?)((\d+))$/u.exec(e);return n?.[1]!==void 0&&n[2]!==void 0?`${n[1]}(${BigInt(n[2])+1n})`:`${e} (1)`}function nf(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let rf=Object.freeze({referenceCount:0,retainedBy:nf({})});async function af(e,t){if(t===void 0)return e;let n=Promise.withResolvers(),r=()=>{n.reject(t.reason)};t.addEventListener(`abort`,r,{once:!0});try{t.aborted&&r(),await Promise.race([e,n.promise])}finally{t.removeEventListener(`abort`,r)}}var of=class{sessionId;record;releaseReference;released=new AbortController;readiness=Promise.withResolvers();ready=this.readiness.promise;constructor(e,t,n){this.sessionId=e,this.record=t,this.releaseReference=n,this.ready.catch(()=>{})}get binding(){if(this.record===void 0||!this.record.live)throw Error(`Session reference "${this.sessionId}" is released`);return this.record.binding}attachOpening(e,t){let n=t===void 0?this.released.signal:AbortSignal.any([this.released.signal,t]);af(e,n).then(()=>{try{n.throwIfAborted(),this.readiness.resolve(this.binding)}catch(e){this.readiness.reject(e)}},e=>{this.readiness.reject(e)})}release(){let e=/* @__PURE__ */ Error(`Session reference "${this.sessionId}" is released`),t=this.releaseReference;this.released.abort(e),this.readiness.reject(e),this.record=void 0,this.releaseReference=void 0,t?.()}[Symbol.dispose](){this.release()}},sf=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new Yd(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}loadSummary(e){return this.manager.loadSummary(e)}loadMore(){return this.manager.loadMore()}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new Qd(t.error,e.sessionId);return this.projectList(),t.value.sessionId}async fork(e){let t=e.increaseTitle?this.list.getSnapshot().byId[e.sessionId]?.title:void 0,n=await this.manager.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:p(e.atSeq)}});if(!n.ok)throw new $d(n.error,e.sessionId);this.projectList();let r=n.value.sessionId;if(e.onCreated?.(r),t!==void 0){let e=await this.manager.rename(r,tf(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:nf({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new of(e,n,()=>{if(!n.live)return;let r=n.retention.referenceCount-1,{[t]:i=0,...a}=n.retention.retainedBy,o=i>1?{...a,[t]:i-1}:a;n.retention=r===0?rf:Object.freeze({referenceCount:r,retainedBy:nf(o)}),r===0?this.retireScope(e,n):this.publishRetention(e)});return this.list.getSnapshot().byId[e]===void 0&&this.manager.subagentAddress(e)!==void 0&&this.projectList(),this.publishRetention(e),i}retentionSnapshot(e){return this.scopes.get(e)?.retention??rf}publishRetention(e){let t=this.list.getSnapshot(),n=t.byId[e],r=this.retentionSnapshot(e).retainedBy;n!==void 0&&n.retainedBy!==r&&this.list.set({...t,byId:{...t.byId,[e]:{...n,retainedBy:r}}});let i=this.retainObservers.get(e),o=this.retentionSnapshot(e);i!==void 0&&i.published!==o&&(i.published=o,(0,a.notifySubscribers)(i.listeners,`[session-controller] reference sources`))}retireScope(e,t,n=!0){if(!t.live)return;t.live=!1,this.scopes.get(e)===t&&this.scopes.delete(e),t.session.unbindScope();let r=this.manager.drop(e,t.session);this.projectList(),this.publishRetention(e),this.startScopeDrop(e,t,n,r)}materializeScope(e){let{fiber:t,ctx:n}=_e(this.rootCtx,e),r=this.manager.get(e);r.bindScope(n);let i={fiber:t,ctx:n,binding:{sessionId:e,session:r,eventSource:r.eventSource,ctx:n},session:r,retention:rf,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,headRefreshRevision:c,summaryOnlyIds:l}=this.manager.getListSnapshot(),u=[],d={};for(let e of t)u.push(e.sessionId),d[e.sessionId]={id:e.sessionId,displayTitle:ef(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:this.retentionSnapshot(e.sessionId).retainedBy,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=d[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?d[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(d[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(d[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;d[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:u,byId:d,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,headRefreshRevision:c??0,summaryOnlyIds:l??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let cf=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function lf(e){let t=e.remote,n=e.get(`connection`),r=new sf(e,t);e.remote.$on(`api-session/added`,e=>{r.handleSessionAdded(e)}),e.remote.$on(`api-session/removed`,e=>{r.handleSessionRemoved(e)}),e.remote.$on(`api-session/status`,(e,t)=>{r.handleSessionStatus(e,t)}),e.remote.$on(`api-session/activity`,(e,t)=>{r.handleSessionActivity(e,t)}),e.remote.$on(`api-session/error`,(e,t)=>{r.handleSessionError(e,t)});let i,a=()=>{if(n.generation.getSnapshot()===void 0)return;let e=i;i=void 0,e?.dispose(),r.handleConnected();let a=fe(t,{accept:e=>{i===a&&r.handleControlFrame(e)},failed:e=>{i===a&&console.error(`[session-controller] control stream failed:`,e)}});i=a,a.start()};e.effect(()=>n.generation.subscribe(a),`session-controller.client.generation`),a(),e.typert.contexts.registerClient(`agent`,{identity:e=>r.sessionOf(e)?.sessionId,resolve:e=>{let t=r.retainAgentScope(e);return c(t.binding.ctx,()=>{t.release()})}}),e.effect(()=>async()=>{await i?.dispose()},`session-controller.client.control`)}return n.MutableSessionEventSource=Od,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=Qd,n.SessionEventStream=pe,n.SessionForkError=$d,n.apply=lf,n.createScope=_e,n.createSessionControlStream=fe,n.inject=cf,n.scopeOf=ve,t.exports}});
|
|
138
|
+
n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function Zd(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function Qd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;(e.type===`image`||e.type===`file`)&&typeof e.attachment==`object`&&e.attachment!==null&&t.push(e.attachment)}return t}var $d=class{views=/* @__PURE__ */ new Map;take(e){let t=this.views.get(e);return this.views.delete(e),t}remember(e,t){if(this.views.delete(e),this.views.set(e,t),this.views.size<=8)return;let n=this.views.keys().next().value;return this.views.delete(n),n}delete(e){this.views.delete(e)}clear(){this.views.clear()}};function ef(e){return e===-1?-1:p(e)}let tf=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]);var nf=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new $d;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;listRequestWorkspaceId;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];notifier=new Dd(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r){let t=this.recentViews.remember(e,r);t&&this.projectionStores.get(t)?.discard(du)}return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.listMutations=null,this.listInflight=null,this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new Xd(e,this.remote,{...t===void 0?{}:{address:t,...n===void 0?{}:{parentAvailable:n}},onEngaged:e=>{!this.disposed&&this.retainedIds(this.summaries).has(e.sessionId)&&(this.engagedSessions.has(e.sessionId)||(this.engagedSessions.add(e.sessionId),this.recordMutation({kind:`engaged`,sessionId:e.sessionId})),this.sessions.get(e.sessionId)?.handleBlank(!1))},projections:this.projectionStore(e),cachedView:this.recentViews.take(e)})}effectiveBlank(e){return e.blank&&!this.engagedSessions.has(e.sessionId)}retainedIds(e){let t=new Set(e.map(e=>e.sessionId));for(let e of this.sessions.keys())t.add(e);for(let e of this.addresses.keys())t.add(e);return t}pruneEngagement(e,t){t.has(e)||this.engagedSessions.delete(e)}projectionStore(e){let t=this.projectionStores.get(e);if(t===void 0){t=new Od;let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.values();this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.values()===a&&r.clear():r.seed({...t.value,asOfSeq:ef(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){return this.nextCursor?this.refreshList(this.nextCursor,e):Promise.resolve()}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let n=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0,this.listRequestWorkspaceId=e===void 0?void 0:t;let r=this.summaries,a=[];return this.listMutations=a,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==a)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...r.filter(e=>!o.has(e.sessionId)&&(s||!n&&t.has(e.sessionId)))],l=this.listPhase===`pending`?c:fd(r,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of a)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=a.reduce(rf,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===a&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==a)return;this.listState=`error`,this.listError=e}finally{this.listMutations===a&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=af(r.error);e!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:e,updatedAt:Date.now(),running:!1,blank:!0}})}return r}async fork(e){let t=this.sessions.get(e.sessionId);if(t&&t.getSnapshot().openState!==`open`)return{ok:!1,error:new o(`session/syncing`,`Wait for the Session history to finish synchronizing.`,{})};let n=this.summaries.find(t=>t.sessionId===e.sessionId),r=await this.remote.session.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:e.atSeq}}),i=r.ok?r.value.sessionId:af(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq)),n}mergeSummary(e){this.recordMutation({kind:`upsert`,summary:e}),this.updateParentAvailability()}recordMutation(e){this.disposed||(this.listMutations?.push(e),this.summaries=rf(this.summaries,e),this.notifier.markDirty())}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):(this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq)),this.notifier.markDirty())}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=ef(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,du)}this.notifier.markDirty()}handleSessionAdded(e,t=!0){t&&this.summaryOnlyIds.delete(e.sessionId),this.mergeSummary(e),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let n=this.sessions.get(e.sessionId);n?.handleRestored(),n?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=ef(t.asOfSeq);for(let[r,i]of Object.entries(t.values))n.apply(r,i,e);return}case`cached`:n.applyCached(t.values);return;default:_d(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){this.summaryOnlyIds.delete(e);let t=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`);this.recordMutation(t?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e}),t?this.sessions.get(e)?.handleRunning(!1):(this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved());let n=this.projectionStores.get(e)?.values().subagentCatalog;!t&&(n===void 0||n.length===0)&&this.projectionStores.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e),this.projectionLoads.delete(e);for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e),this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0}),this.updateParentAvailability(),this.sessions.get(e)?.handleRunning(t)}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t})}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(tf);this.listMutations=null,this.listInflight=null,this.nextCursor=void 0,this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=Ed(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);return e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e),{items:this.itemsCache,hasMore:!!this.nextCursor,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,errorWorkspaceId:this.listError&&this.listRequestIsMore?this.listRequestWorkspaceId??null:null,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([e,t])=>[e,{values:t.values(),state:`idle`,error:null,...this.projectionLoads.get(e)}]))}}};function rf(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.find(e=>e.sessionId===t.summary.sessionId);if(n===void 0)return[t.summary,...e];let r={...n,blank:n.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...n.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...n.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...n.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};return r.cwd===n.cwd&&r.parentSessionId===n.parentSessionId&&r.origin===n.origin&&r.blank===n.blank&&r.agentAvailable===n.agentAvailable&&r.running===n.running?[...e]:e.map(e=>e.sessionId===t.summary.sessionId?r:e)}case`remove`:return e.filter(e=>e.sessionId!==t.sessionId);case`status`:return e.map(e=>e.sessionId===t.sessionId&&(e.running!==t.running||e.agentAvailable!==t.agentAvailable||t.running&&e.blank)?{...e,running:t.running,agentAvailable:t.agentAvailable,blank:e.blank&&!t.running}:e);case`activity`:return e.map(e=>e.sessionId===t.sessionId&&t.updatedAt>e.updatedAt?{...e,updatedAt:t.updatedAt}:e);case`engaged`:return e.map(e=>e.sessionId===t.sessionId&&e.blank?{...e,blank:!1}:e)}}function af(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var of=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},sf=class extends Error{rpcError;sourceSessionId;name=`SessionForkError`;constructor(e,t){super(`session fork failed: ${e.code}: ${e.message}`),this.rpcError=e,this.sourceSessionId=t}};function cf(e,t,n){if(e!==void 0)return e;if(t!==void 0&&t!==``){let e=me(t);if(e!==``)return e}return n}function lf(e){let t=/^(.*?)\((\d+)\)$/u.exec(e);if(t?.[1]!==void 0&&t[2]!==void 0)return`${t[1]}(${BigInt(t[2])+1n})`;let n=/^(.*?)((\d+))$/u.exec(e);return n?.[1]!==void 0&&n[2]!==void 0?`${n[1]}(${BigInt(n[2])+1n})`:`${e} (1)`}function uf(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let df=Object.freeze({referenceCount:0,retainedBy:uf({})});async function ff(e,t){if(t===void 0)return e;let n=Promise.withResolvers(),r=()=>{n.reject(t.reason)};t.addEventListener(`abort`,r,{once:!0});try{t.aborted&&r(),await Promise.race([e,n.promise])}finally{t.removeEventListener(`abort`,r)}}var pf=class{sessionId;record;releaseReference;released=new AbortController;readiness=Promise.withResolvers();ready=this.readiness.promise;constructor(e,t,n){this.sessionId=e,this.record=t,this.releaseReference=n,this.ready.catch(()=>{})}get binding(){if(this.record===void 0||!this.record.live)throw Error(`Session reference "${this.sessionId}" is released`);return this.record.binding}attachOpening(e,t){let n=t===void 0?this.released.signal:AbortSignal.any([this.released.signal,t]);ff(e,n).then(()=>{try{n.throwIfAborted(),this.readiness.resolve(this.binding)}catch(e){this.readiness.reject(e)}},e=>{this.readiness.reject(e)})}release(){let e=/* @__PURE__ */ Error(`Session reference "${this.sessionId}" is released`),t=this.releaseReference;this.released.abort(e),this.readiness.reject(e),this.record=void 0,this.releaseReference=void 0,t?.()}[Symbol.dispose](){this.release()}},mf=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new nf(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}loadSummary(e){return this.manager.loadSummary(e)}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new of(t.error,e.sessionId);return this.projectList(),t.value.sessionId}async fork(e){let t=e.increaseTitle?this.list.getSnapshot().byId[e.sessionId]?.title:void 0,n=await this.manager.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:p(e.atSeq)}});if(!n.ok)throw new sf(n.error,e.sessionId);this.projectList();let r=n.value.sessionId;if(e.onCreated?.(r),t!==void 0){let e=await this.manager.rename(r,lf(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:uf({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new pf(e,n,()=>{if(!n.live)return;let r=n.retention.referenceCount-1,{[t]:i=0,...a}=n.retention.retainedBy,o=i>1?{...a,[t]:i-1}:a;n.retention=r===0?df:Object.freeze({referenceCount:r,retainedBy:uf(o)}),r===0?this.retireScope(e,n):this.publishRetention(e)});return this.list.getSnapshot().byId[e]===void 0&&this.manager.subagentAddress(e)!==void 0&&this.projectList(),this.publishRetention(e),i}retentionSnapshot(e){return this.scopes.get(e)?.retention??df}publishRetention(e){let t=this.list.getSnapshot(),n=t.byId[e],r=this.retentionSnapshot(e).retainedBy;n!==void 0&&n.retainedBy!==r&&this.list.set({...t,byId:{...t.byId,[e]:{...n,retainedBy:r}}});let i=this.retainObservers.get(e),o=this.retentionSnapshot(e);i!==void 0&&i.published!==o&&(i.published=o,(0,a.notifySubscribers)(i.listeners,`[session-controller] reference sources`))}retireScope(e,t,n=!0){if(!t.live)return;t.live=!1,this.scopes.get(e)===t&&this.scopes.delete(e),t.session.unbindScope();let r=this.manager.drop(e,t.session);this.projectList(),this.publishRetention(e),this.startScopeDrop(e,t,n,r)}materializeScope(e){let{fiber:t,ctx:n}=_e(this.rootCtx,e),r=this.manager.get(e);r.bindScope(n);let i={fiber:t,ctx:n,binding:{sessionId:e,session:r,eventSource:r.eventSource,ctx:n},session:r,retention:df,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,errorWorkspaceId:c,headRefreshRevision:l,summaryOnlyIds:u}=this.manager.getListSnapshot(),d=[],f={};for(let e of t)d.push(e.sessionId),f[e.sessionId]={id:e.sessionId,displayTitle:cf(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:this.retentionSnapshot(e.sessionId).retainedBy,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=f[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?f[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(f[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(f[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;f[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:d,byId:f,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,listErrorWorkspaceId:c,headRefreshRevision:l??0,summaryOnlyIds:u??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let hf=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function gf(e){let t=e.remote,n=e.get(`connection`),r=new mf(e,t);e.remote.$on(`api-session/added`,e=>{r.handleSessionAdded(e)}),e.remote.$on(`api-session/removed`,e=>{r.handleSessionRemoved(e)}),e.remote.$on(`api-session/status`,(e,t)=>{r.handleSessionStatus(e,t)}),e.remote.$on(`api-session/activity`,(e,t)=>{r.handleSessionActivity(e,t)}),e.remote.$on(`api-session/error`,(e,t)=>{r.handleSessionError(e,t)});let i,a=()=>{if(n.generation.getSnapshot()===void 0)return;let e=i;i=void 0,e?.dispose(),r.handleConnected();let a=fe(t,{accept:e=>{i===a&&r.handleControlFrame(e)},failed:e=>{i===a&&console.error(`[session-controller] control stream failed:`,e)}});i=a,a.start()};e.effect(()=>n.generation.subscribe(a),`session-controller.client.generation`),a(),e.typert.contexts.registerClient(`agent`,{identity:e=>r.sessionOf(e)?.sessionId,resolve:e=>{let t=r.retainAgentScope(e);return c(t.binding.ctx,()=>{t.release()})}}),e.effect(()=>async()=>{await i?.dispose()},`session-controller.client.control`)}return n.MutableSessionEventSource=Fd,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=of,n.SessionEventStream=pe,n.SessionForkError=sf,n.apply=gf,n.createScope=_e,n.createSessionControlStream=fe,n.inject=hf,n.scopeOf=ve,t.exports}});
|