@codexhost/cli-darwin-arm64 0.18.0-beta.3 → 0.18.0-beta.4
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 +9 -4
- package/app/console-web.js +9 -4
- package/app/desktop-controller.mjs +9 -4
- package/app/host-runtime.mjs +4751 -2746
- package/app/plugins/antigravity/plugin.mjs +9 -4
- package/app/plugins/claude-code/plugin.mjs +129 -58
- package/app/plugins/codebuddy/plugin.mjs +9 -4
- package/app/plugins/codex-usage/plugin.mjs +9 -4
- package/app/plugins/copilot/plugin.mjs +9 -4
- package/app/plugins/cursor-cli/plugin.mjs +9 -4
- package/app/plugins/deepseek-harness/plugin.mjs +9 -4
- package/app/plugins/devin/plugin.mjs +9 -4
- package/app/plugins/grok/plugin.mjs +9 -4
- package/app/plugins/hermes/plugin.mjs +9 -4
- package/app/plugins/kimi-code/plugin.mjs +9 -4
- package/app/plugins/kiro-cli/plugin.mjs +9 -4
- package/app/plugins/omp/plugin.mjs +9 -4
- package/app/plugins/opencode/plugin.mjs +9 -4
- package/app/plugins/pi/plugin.mjs +9 -4
- package/app/plugins/qoder/plugin.mjs +9 -4
- package/app/plugins/qoder-cn/plugin.mjs +9 -4
- package/app/plugins/qwen-code/plugin.mjs +9 -4
- package/app/plugins/workbuddy/plugin.mjs +9 -4
- package/app/plugins/zcode/plugin.mjs +9 -4
- package/app/renderer-extension.js +9 -4
- package/app/web/assets/{index-aKvkfNJN.js → index-D1dOzBMI.js} +2 -2
- package/app/web/codexhost-settings.js +9 -4
- package/app/web/index.html +1 -1
- package/app/web/plugins/deepseek-ai__dsh-api-gateway/client.js +1 -1
- 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 +3 -3
- package/app/web/plugins/deepseek-ai__dsh-client-connection/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +63 -63
- package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +8 -8
- package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
- package/app/web/plugins/deepseek-ai__dsh-client-ui-settings/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +2 -2
- package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +2 -2
- package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +8 -12
- package/app/web/plugins.json +4 -0
- package/app/web-modules/server.mjs +374 -154
- package/bin/codexhost +0 -0
- package/libexec/codexhost-shim +0 -0
- package/libexec/codexhost-updater +0 -0
- package/package.json +1 -1
|
@@ -119,7 +119,7 @@ function Bi(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...y(n)})}//
|
|
|
119
119
|
function Vi(e,t){let n=/* @__PURE__ */ Hi(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(nt(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(nt(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
|
|
120
120
|
function Hi(e,t){let n=new S({check:`custom`,...y(t)});return n._zod.check=e,n}function Ui(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??Rr,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 T(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,T(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`&&E(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 Wi(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 Gi(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:qi(t,`input`,e.processors),output:qi(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function E(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 E(r.element,n);if(r.type===`set`)return E(r.valueType,n);if(r.type===`lazy`)return E(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 E(r.innerType,n);if(r.type===`intersection`)return E(r.left,n)||E(r.right,n);if(r.type===`record`||r.type===`map`)return E(r.keyType,n)||E(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:E(r.in,n)||E(r.out,n);if(r.type===`object`){for(let e in r.shape)if(E(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(E(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(E(e,n))return!0;return!!(r.rest&&E(r.rest,n))}return!1}let Ki=(e,t={})=>n=>{let r=Ui({...n,processors:t});return T(e,r),Wi(r,e),Gi(r,e)},qi=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Ui({...i??{},target:a,io:t,processors:n});return T(e,o),Wi(o,e),Gi(o,e)},Ji={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Yi=(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=Ji[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}))])}},Xi=(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)},Zi=(e,t,n,r)=>{n.type=`boolean`},Qi=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},$i=(e,t,n,r)=>{n.not={}},ea=(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},ta=(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}},na=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},ra=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},ia=(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=T(a.element,t,{...r,path:[...r.path,`items`]})},aa=(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]=T(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=T(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},oa=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>T(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},sa=(e,t,n,r)=>{let i=e._zod.def,a=T(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=T(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]]},ca=(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)=>T(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?T(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)},la=(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=T(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=T(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=T(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)}},ua=(e,t,n,r)=>{let i=e._zod.def,a=T(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`}]},da=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},fa=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},pa=(e,t,n,r)=>{let i=e._zod.def;T(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)))},ma=(e,t,n,r)=>{let i=e._zod.def;T(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},ha=(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;T(o,t,r);let s=t.seen.get(e);s.ref=o},ga=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},_a=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},va=(e,t,n,r)=>{let i=e._zod.innerType;T(i,t,r);let a=t.seen.get(e);a.ref=i},ya=/*@__PURE__*/ h(`ZodISODateTime`,(e,t)=>{An.init(e,t),A.init(e,t)});function ba(e){return/* @__PURE__ */ ci(ya,e)}let xa=/*@__PURE__*/ h(`ZodISODate`,(e,t)=>{jn.init(e,t),A.init(e,t)});function Sa(e){return/* @__PURE__ */ li(xa,e)}let Ca=/*@__PURE__*/ h(`ZodISOTime`,(e,t)=>{Mn.init(e,t),A.init(e,t)});function wa(e){return/* @__PURE__ */ ui(Ca,e)}let Ta=/*@__PURE__*/ h(`ZodISODuration`,(e,t)=>{Nn.init(e,t),A.init(e,t)});function Ea(e){return/* @__PURE__ */ di(Ta,e)}let D=/*@__PURE__*/ h(`ZodError`,(e,t)=>{it.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>st(e,t)},flatten:{value:t=>ot(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}),Da=/* @__PURE__ */ ct(D),Oa=/* @__PURE__ */ lt(D),ka=/* @__PURE__ */ ut(D),Aa=/* @__PURE__ */ ft(D),ja=/* @__PURE__ */ mt(D),Ma=/* @__PURE__ */ ht(D),Na=/* @__PURE__ */ gt(D),Pa=/* @__PURE__ */ _t(D),Fa=/* @__PURE__ */ vt(D),Ia=/* @__PURE__ */ yt(D),La=/* @__PURE__ */ bt(D),Ra=/* @__PURE__ */ xt(D),za=/* @__PURE__ */ new WeakMap;function Ba(e,t,n){let r=Object.getPrototypeOf(e),i=za.get(r);if(i||(i=/* @__PURE__ */ new Set,za.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 O=/*@__PURE__*/ h(`ZodType`,(e,t)=>(C.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:qi(e,`input`),output:qi(e,`output`)}}),e.toJSONSchema=Ki(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Da(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ka(e,t,n),e.parseAsync=async(t,n)=>Oa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Aa(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>ja(e,t,n),e.decode=(t,n)=>Ma(e,t,n),e.encodeAsync=async(t,n)=>Na(e,t,n),e.decodeAsync=async(t,n)=>Pa(e,t,n),e.safeEncode=(t,n)=>Fa(e,t,n),e.safeDecode=(t,n)=>Ia(e,t,n),e.safeEncodeAsync=async(t,n)=>La(e,t,n),e.safeDecodeAsync=async(t,n)=>Ra(e,t,n),Ba(e,`ZodType`,{check(...e){let t=this.def;return this.clone(v(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 He(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(ts(e,t))},superRefine(e,t){return this.check(ns(e,t))},overwrite(e){return this.check(/* @__PURE__ */ Mi(e))},optional(){return Po(this)},exactOptional(){return Io(this)},nullable(){return Ro(this)},nullish(){return Po(Ro(this))},nonoptional(e){return Wo(this,e)},array(){return N(this)},or(e){return I([this,e])},and(e){return To(this,e)},transform(e){return Jo(this,Mo(e))},default(e){return Bo(this,e)},prefault(e){return Ho(this,e)},catch(e){return Ko(this,e)},pipe(e){return Jo(this,e)},readonly(){return Xo(this)},describe(e){let t=this.clone();return Rr.add(t,{description:e}),t},meta(...e){if(e.length===0)return Rr.get(this);let t=this.clone();return Rr.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 Rr.get(e)?.description},configurable:!0}),e)),Va=/*@__PURE__*/ h(`_ZodString`,(e,t)=>{vn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ba(e,`_ZodString`,{regex(...e){return this.check(/* @__PURE__ */ Ei(...e))},includes(...e){return this.check(/* @__PURE__ */ ki(...e))},startsWith(...e){return this.check(/* @__PURE__ */ Ai(...e))},endsWith(...e){return this.check(/* @__PURE__ */ ji(...e))},min(...e){return this.check(/* @__PURE__ */ wi(...e))},max(...e){return this.check(/* @__PURE__ */ Ci(...e))},length(...e){return this.check(/* @__PURE__ */ Ti(...e))},nonempty(...e){return this.check(/* @__PURE__ */ wi(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ Di(e))},uppercase(e){return this.check(/* @__PURE__ */ Oi(e))},trim(){return this.check(/* @__PURE__ */ Pi())},normalize(...e){return this.check(/* @__PURE__ */ Ni(...e))},toLowerCase(){return this.check(/* @__PURE__ */ Fi())},toUpperCase(){return this.check(/* @__PURE__ */ Ii())},slugify(){return this.check(/* @__PURE__ */ Li())}})}),Ha=/*@__PURE__*/ h(`ZodString`,(e,t)=>{vn.init(e,t),Va.init(e,t),e.email=t=>e.check(/* @__PURE__ */ Br(Ua,t)),e.url=t=>e.check(/* @__PURE__ */ Kr(Ka,t)),e.jwt=t=>e.check(/* @__PURE__ */ si(co,t)),e.emoji=t=>e.check(/* @__PURE__ */ qr(Ja,t)),e.guid=t=>e.check(/* @__PURE__ */ Vr(Wa,t)),e.uuid=t=>e.check(/* @__PURE__ */ Hr(Ga,t)),e.uuidv4=t=>e.check(/* @__PURE__ */ Ur(Ga,t)),e.uuidv6=t=>e.check(/* @__PURE__ */ Wr(Ga,t)),e.uuidv7=t=>e.check(/* @__PURE__ */ Gr(Ga,t)),e.nanoid=t=>e.check(/* @__PURE__ */ Jr(Ya,t)),e.guid=t=>e.check(/* @__PURE__ */ Vr(Wa,t)),e.cuid=t=>e.check(/* @__PURE__ */ Yr(Xa,t)),e.cuid2=t=>e.check(/* @__PURE__ */ Xr(Za,t)),e.ulid=t=>e.check(/* @__PURE__ */ Zr(Qa,t)),e.base64=t=>e.check(/* @__PURE__ */ ii(ao,t)),e.base64url=t=>e.check(/* @__PURE__ */ ai(oo,t)),e.xid=t=>e.check(/* @__PURE__ */ Qr($a,t)),e.ksuid=t=>e.check(/* @__PURE__ */ $r(eo,t)),e.ipv4=t=>e.check(/* @__PURE__ */ ei(to,t)),e.ipv6=t=>e.check(/* @__PURE__ */ ti(no,t)),e.cidrv4=t=>e.check(/* @__PURE__ */ ni(ro,t)),e.cidrv6=t=>e.check(/* @__PURE__ */ ri(io,t)),e.e164=t=>e.check(/* @__PURE__ */ oi(so,t)),e.datetime=t=>e.check(ba(t)),e.date=t=>e.check(Sa(t)),e.time=t=>e.check(wa(t)),e.duration=t=>e.check(Ea(t))});function k(e){return/* @__PURE__ */ zr(Ha,e)}let A=/*@__PURE__*/ h(`ZodStringFormat`,(e,t)=>{w.init(e,t),Va.init(e,t)}),Ua=/*@__PURE__*/ h(`ZodEmail`,(e,t)=>{xn.init(e,t),A.init(e,t)}),Wa=/*@__PURE__*/ h(`ZodGUID`,(e,t)=>{yn.init(e,t),A.init(e,t)}),Ga=/*@__PURE__*/ h(`ZodUUID`,(e,t)=>{bn.init(e,t),A.init(e,t)}),Ka=/*@__PURE__*/ h(`ZodURL`,(e,t)=>{Sn.init(e,t),A.init(e,t)});function qa(e){return/* @__PURE__ */ Kr(Ka,e)}let Ja=/*@__PURE__*/ h(`ZodEmoji`,(e,t)=>{Cn.init(e,t),A.init(e,t)}),Ya=/*@__PURE__*/ h(`ZodNanoID`,(e,t)=>{wn.init(e,t),A.init(e,t)}),Xa=/*@__PURE__*/ h(`ZodCUID`,(e,t)=>{Tn.init(e,t),A.init(e,t)}),Za=/*@__PURE__*/ h(`ZodCUID2`,(e,t)=>{En.init(e,t),A.init(e,t)}),Qa=/*@__PURE__*/ h(`ZodULID`,(e,t)=>{Dn.init(e,t),A.init(e,t)}),$a=/*@__PURE__*/ h(`ZodXID`,(e,t)=>{On.init(e,t),A.init(e,t)}),eo=/*@__PURE__*/ h(`ZodKSUID`,(e,t)=>{kn.init(e,t),A.init(e,t)}),to=/*@__PURE__*/ h(`ZodIPv4`,(e,t)=>{Pn.init(e,t),A.init(e,t)}),no=/*@__PURE__*/ h(`ZodIPv6`,(e,t)=>{Fn.init(e,t),A.init(e,t)}),ro=/*@__PURE__*/ h(`ZodCIDRv4`,(e,t)=>{In.init(e,t),A.init(e,t)}),io=/*@__PURE__*/ h(`ZodCIDRv6`,(e,t)=>{Ln.init(e,t),A.init(e,t)}),ao=/*@__PURE__*/ h(`ZodBase64`,(e,t)=>{zn.init(e,t),A.init(e,t)}),oo=/*@__PURE__*/ h(`ZodBase64URL`,(e,t)=>{Vn.init(e,t),A.init(e,t)}),so=/*@__PURE__*/ h(`ZodE164`,(e,t)=>{Hn.init(e,t),A.init(e,t)}),co=/*@__PURE__*/ h(`ZodJWT`,(e,t)=>{Wn.init(e,t),A.init(e,t)}),lo=/*@__PURE__*/ h(`ZodNumber`,(e,t)=>{Gn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),Ba(e,`ZodNumber`,{gt(e,t){return this.check(/* @__PURE__ */ bi(e,t))},gte(e,t){return this.check(/* @__PURE__ */ xi(e,t))},min(e,t){return this.check(/* @__PURE__ */ xi(e,t))},lt(e,t){return this.check(/* @__PURE__ */ vi(e,t))},lte(e,t){return this.check(/* @__PURE__ */ yi(e,t))},max(e,t){return this.check(/* @__PURE__ */ yi(e,t))},int(e){return this.check(fo(e))},safe(e){return this.check(fo(e))},positive(e){return this.check(/* @__PURE__ */ bi(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ xi(0,e))},negative(e){return this.check(/* @__PURE__ */ vi(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ yi(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Si(e,t))},step(e,t){return this.check(/* @__PURE__ */ Si(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 j(e){return/* @__PURE__ */ fi(lo,e)}let uo=/*@__PURE__*/ h(`ZodNumberFormat`,(e,t)=>{Kn.init(e,t),lo.init(e,t)});function fo(e){return/* @__PURE__ */ pi(uo,e)}let po=/*@__PURE__*/ h(`ZodBoolean`,(e,t)=>{qn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r)});function M(e){return/* @__PURE__ */ mi(po,e)}let mo=/*@__PURE__*/ h(`ZodNull`,(e,t)=>{Jn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r)});function ho(e){return/* @__PURE__ */ hi(mo,e)}let go=/*@__PURE__*/ h(`ZodUnknown`,(e,t)=>{Yn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function _o(){return/* @__PURE__ */ gi(go)}let vo=/*@__PURE__*/ h(`ZodNever`,(e,t)=>{Xn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r)});function yo(e){return/* @__PURE__ */ _i(vo,e)}let bo=/*@__PURE__*/ h(`ZodArray`,(e,t)=>{Qn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ia(e,t,n,r),e.element=t.element,Ba(e,`ZodArray`,{min(e,t){return this.check(/* @__PURE__ */ wi(e,t))},nonempty(e){return this.check(/* @__PURE__ */ wi(1,e))},max(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},length(e,t){return this.check(/* @__PURE__ */ Ti(e,t))},unwrap(){return this.element}})});function N(e,t){return/* @__PURE__ */ Ri(bo,e,t)}let xo=/*@__PURE__*/ h(`ZodObject`,(e,t)=>{rr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aa(e,t,n,r),_(e,`shape`,()=>t.shape),Ba(e,`ZodObject`,{keyof(){return z(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:_o()})},loose(){return this.clone({...this._zod.def,catchall:_o()})},strict(){return this.clone({...this._zod.def,catchall:yo()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return qe(this,e)},safeExtend(e){return Je(this,e)},merge(e){return Ye(this,e)},pick(e){return Ge(this,e)},omit(e){return Ke(this,e)},partial(...e){return Xe(No,this,e[0])},required(...e){return Ze(Uo,this,e[0])}})});function P(e,t){let n={type:`object`,shape:e??{},...y(t)};return new xo(n)}function F(e,t){return new xo({type:`object`,shape:e,catchall:yo(),...y(t)})}let So=/*@__PURE__*/ h(`ZodUnion`,(e,t)=>{ar.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),e.options=t.options});function I(e,t){return new So({type:`union`,options:e,...y(t)})}let Co=/*@__PURE__*/ h(`ZodDiscriminatedUnion`,(e,t)=>{So.init(e,t),or.init(e,t)});function L(e,t,n){return new Co({type:`union`,options:t,discriminator:e,...y(n)})}let wo=/*@__PURE__*/ h(`ZodIntersection`,(e,t)=>{sr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sa(e,t,n,r)});function To(e,t){return new wo({type:`intersection`,left:e,right:t})}let Eo=/*@__PURE__*/ h(`ZodTuple`,(e,t)=>{ur.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ca(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function Do(e,t,n){let r=t instanceof C;return new Eo({type:`tuple`,items:e,rest:r?t:null,...y(r?n:t)})}let Oo=/*@__PURE__*/ h(`ZodRecord`,(e,t)=>{mr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>la(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function R(e,t,n){return!t||!t._zod?new Oo({type:`record`,keyType:k(),valueType:e,...y(t)}):new Oo({type:`record`,keyType:e,valueType:t,...y(n)})}let ko=/*@__PURE__*/ h(`ZodEnum`,(e,t)=>{hr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(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 ko({...t,checks:[],...y(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 ko({...t,checks:[],...y(r),entries:i})}});function z(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ko({type:`enum`,entries:n,...y(t)})}let Ao=/*@__PURE__*/ h(`ZodLiteral`,(e,t)=>{gr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(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 B(e,t){return new Ao({type:`literal`,values:Array.isArray(e)?e:[e],...y(t)})}let jo=/*@__PURE__*/ h(`ZodTransform`,(e,t)=>{_r.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ra(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(nt(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(nt(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 Mo(e){return new jo({type:`transform`,transform:e})}let No=/*@__PURE__*/ h(`ZodOptional`,(e,t)=>{yr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Po(e){return new No({type:`optional`,innerType:e})}let Fo=/*@__PURE__*/ h(`ZodExactOptional`,(e,t)=>{br.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Fo({type:`optional`,innerType:e})}let Lo=/*@__PURE__*/ h(`ZodNullable`,(e,t)=>{xr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ua(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ro(e){return new Lo({type:`nullable`,innerType:e})}let zo=/*@__PURE__*/ h(`ZodDefault`,(e,t)=>{Sr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bo(e,t){return new zo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}let Vo=/*@__PURE__*/ h(`ZodPrefault`,(e,t)=>{wr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ho(e,t){return new Vo({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}let Uo=/*@__PURE__*/ h(`ZodNonOptional`,(e,t)=>{Tr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>da(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wo(e,t){return new Uo({type:`nonoptional`,innerType:e,...y(t)})}let Go=/*@__PURE__*/ h(`ZodCatch`,(e,t)=>{Dr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ma(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ko(e,t){return new Go({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let qo=/*@__PURE__*/ h(`ZodPipe`,(e,t)=>{Or.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ha(e,t,n,r),e.in=t.in,e.out=t.out});function Jo(e,t){return new qo({type:`pipe`,in:e,out:t})}let Yo=/*@__PURE__*/ h(`ZodReadonly`,(e,t)=>{Ar.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ga(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xo(e){return new Yo({type:`readonly`,innerType:e})}let Zo=/*@__PURE__*/ h(`ZodLazy`,(e,t)=>{Mr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>va(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Qo(e){return new Zo({type:`lazy`,getter:e})}let $o=/*@__PURE__*/ h(`ZodCustom`,(e,t)=>{Nr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>na(e,t,n,r)});function es(e,t){return/* @__PURE__ */ zi($o,e??(()=>!0),t)}function ts(e,t={}){return/* @__PURE__ */ Bi($o,e,t)}function ns(e,t){return/* @__PURE__ */ Vi(e,t)}function V(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 rs=I([k(),j(),M(),ho()]);function is(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 as=es(is,{message:`JSON value must not contain circular references`}),os=Qo(()=>I([rs,N(os),R(k(),os)])),H=as.pipe(os);as.pipe(N(os));let ss=as.pipe(R(k(),os)),cs=F({code:k().min(1),message:k().min(1),retryable:M(),diagnostic:k().min(1).optional(),stage:k().min(1).optional(),durationMs:j().int().nonnegative().optional(),stderrTail:k().min(1).optional()}).superRefine(V([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),ls=k().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),us=e=>k().min(1).max(e).refine(e=>e.trim().length>0),ds=R(ls,P({label:us(256).optional(),description:us(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),fs=R(ls,us(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),ps=k().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),U=ps.brand(),W=ps.brand(),ms=ps.brand();ps.brand(),ps.brand();let hs=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),G=hs.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),gs=P({modes:N(P({id:G,label:hs.max(256),description:hs.max(1024).optional(),dangerous:M().optional(),localizations:ds.optional()}).strict()).min(1).max(32),defaultModeId:G}).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`]})});P({threadId:W,permissionModeId:G}).strict();let K=j().int().safe().nonnegative(),_s=j().finite().nonnegative(),vs=j().finite().min(0).max(100),ys=P({value:_s,turnId:k().min(1).max(1024),at:K}).strict();P({outputTokensPerSecond:ys.optional(),timeToFirstOutputMs:ys.extend({value:K}).optional()}).strict();let bs=e=>fs.refine(t=>Object.values(t).every(t=>t.length<=e)),xs=P({composerIndicators:N(P({kind:B(`countdown`),id:k().min(1).max(64),expiresAtUnix:K,label:bs(256).optional(),tooltip:bs(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:K.optional(),cachedInputTokens:K.optional(),cacheWriteInputTokens:K.optional(),outputTokens:K.optional(),outputTokensPerSecond:_s.optional(),apiOutputTokensPerSecond:_s.optional(),reasoningOutputTokens:K.optional(),totalTokens:K.optional(),totalCostUsd:_s.optional(),totalCredits:_s.optional(),contextUsagePercent:_s.optional(),cacheHitRatePercent:vs.optional(),contextWindowTokens:K.optional(),contextUsedTokens:K.optional(),planFiveHourUsedPercent:vs.optional(),planFiveHourResetsAtUnix:K.optional(),planSevenDayUsedPercent:vs.optional(),planSevenDayResetsAtUnix:K.optional(),sessionCacheHitRatePercent:vs.optional(),timeToFirstOutputMs:K.optional(),costSource:z([`publicPrice`,`native`]).optional(),unpricedModels:N(k().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`]})}),Ss=j().finite().min(0).max(100),Cs=z([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),ws=P({id:k().min(1).max(256),label:k().min(1).max(256),localizations:ds.optional()}).strict(),Ts=P({product:k().min(1),periodType:Cs.optional(),scope:ws.optional(),localizations:ds.optional(),used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),usagePercent:Ss,resetsAt:k().min(1).optional()}).strict(),Es=P({availableCount:j().int().safe().positive(),nextExpiresAt:k().min(1).optional(),expiresAt:N(k().min(1)).min(1).max(32).optional()}).strict(),Ds=P({used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),label:k().min(1).optional(),scope:ws.optional(),localizations:ds.optional(),usedPercent:Ss,resetsAt:k().min(1).optional(),periodType:Cs,productUsage:N(Ts).min(1).optional(),resetCredits:Es.optional()}).strict();P({threadId:W,refresh:B(`exact`).optional()}).strict(),P({threadId:W,usage:xs.nullable(),accountCredits:Ds.optional(),accountCreditsSupported:M().optional()}).strict();let q=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),J=P({id:q.max(512).regex(/^[A-Za-z0-9._~-]+$/u,`Model Ref must use transport-safe opaque characters`).brand()}).strict(),Y=q.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Os=q.max(256),ks=P({id:Y,label:q.max(256)}).strict(),As=P({ref:J,label:q.max(256),resolvedModelLabel:Os.optional(),fastModel:J.optional(),supportedThinkingOptionIds:N(Y).optional()}).strict(),js=N(ks).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)}),Ms=P({models:N(As),defaultModel:J.optional(),thinkingOptions:js,defaultThinkingOptionId:Y.optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set,r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.has(a.ref.id)&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.add(a.ref.id),a.fastModel&&((n.has(a.fastModel.id)||e.models.some(e=>e.ref.id===a.fastModel?.id))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.add(a.fastModel.id));let o=/* @__PURE__ */ new Set;for(let[e,n]of(a.supportedThinkingOptionIds??[]).entries())o.has(n)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,e]}),o.add(n),r.has(n)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,e]})}e.defaultModel&&!n.has(e.defaultModel.id)&&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`]})}),Ns=P({fork:M(),forkAcrossCwd:M(),rollbackLastTurn:M()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Ps=z([`live`,`atCreate`]),Fs=P({configuration:P({selectModel:M(),selectThinkingOption:M(),selectPermissionMode:M(),permissionModeScope:Ps.default(`live`)}).strict(),history:Ns,subagents:P({observe:M(),readTranscript:M()}).strict().optional(),autonomousTurns:P({observe:M()}).strict().optional(),steer:M().optional()}).strict();P({effectiveModel:J.optional(),resolvedModelLabel:Os.optional(),effectiveThinkingOptionId:Y.optional(),availableThinkingOptions:js.optional(),effectivePermissionModeId:G.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 Is=P({open:B(!0)}).strict();I([P({status:B(`ready`),catalog:Ms,permissionModes:gs.optional(),capabilities:Fs,webUi:Is.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`]})}),P({status:z([`notInstalled`,`unavailable`,`error`]),error:cs}).strict()]),P({harnessId:U,cwd:q.max(16384).optional(),refresh:M().optional(),purpose:B(`availability`).optional()}).strict(),P({harnessId:U}).strict(),P({}).strict(),P({threadId:W,model:J}).strict(),P({threadId:W,thinkingOptionId:Y}).strict(),P({threadId:W,includeReferenceCapability:M().optional()}).strict(),L(`owner`,[P({owner:B(`codex`),locked:M(),effectiveModel:J.optional(),resolvedModelLabel:Os.optional(),effectiveThinkingOptionId:Y.optional(),effectivePermissionModeId:G.optional(),history:Ns.optional(),supportsThreadReferences:B(!0).optional()}).strict(),P({owner:B(`external`),harnessId:q.max(256),transportModelId:q.max(1024),effectiveModel:J.optional(),resolvedModelLabel:Os.optional(),effectiveThinkingOptionId:Y.optional(),availableThinkingOptions:js.optional(),effectivePermissionModeId:G.optional(),history:Ns,usage:xs.optional(),locked:B(!0)}).strict()]),P({threadIds:N(W).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 Ls=L(`owner`,[P({threadId:W,owner:B(`codex`)}).strict(),P({threadId:W,owner:B(`external`),harnessId:k().max(256).pipe(U)}).strict()]);P({threads:N(Ls).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)}),P({threadId:W,text:k().optional()}).strict(),P({kind:B(`application`),value:k().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),xe}}).pipe(P({expectedTurnId:ms,clientUserMessageId:k().min(1),delivery:z([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),z([`activeTurn`,`newTurn`]),P({delivery:z([`official`,`activeTurn`,`newTurn`])}).strict(),P({threadIds:N(k().min(1))}).strict(),P({threadId:k().min(1).max(1024),pinned:M()}).strict(),P({prompt:k().max(16384).optional()}).strict(),P({projects:N(P({id:k(),name:k(),rootPaths:N(k())})),assignments:R(k(),k()),projectless:N(k()),pinned:N(k())});let Rs=R(k(),_o()),zs=P({epoch:k().uuid(),sequence:j().int().nonnegative()});L(`type`,[P({type:B(`display-settings-changed`),cursor:zs}),P({type:B(`preferences-changed`),cursor:zs,revision:j().int().nonnegative()}),P({type:B(`hello`),version:B(1),cursor:zs,reset:M()}),P({type:B(`changed`),cursor:zs,threadId:k().min(1),method:k().min(1)})]);let Bs=L(`type`,[P({type:B(`text`),id:k(),prompt:k(),secret:M().optional(),optional:M().optional()}),P({type:B(`choice`),id:k(),prompt:k(),multiple:M(),allowOther:M(),optional:M().optional(),options:N(P({value:k(),label:k(),description:k().optional()}))})]),Vs=L(`type`,[P({type:B(`approval`),title:k(),description:k().optional(),subject:_o().optional(),actions:N(P({id:k(),label:k(),effect:k()}))}),P({type:B(`question`),title:k().optional(),questions:N(Bs)})]),Hs=P({requestId:I([k(),j().int()]),threadId:k(),kind:z([`approval`,`question`]),interaction:Vs,request:Rs}),Us=P({id:k().min(1),clientUserMessageId:k().min(1),input:N(Rs),presentationInput:N(Rs).nullable().optional()}).passthrough();P({fields:N(P({path:N(I([k(),j().int().nonnegative()])),originalLength:j().int().nonnegative()}))});let Ws=P({id:k().min(1),status:k().min(1),items:N(P({id:k().min(1),type:k().min(1)}).passthrough()),codexhostFileOperations:N(P({beforeItemId:k().nullable(),item:P({id:k().min(1),type:k().min(1)}).passthrough()})).optional(),error:P({message:k().optional()}).passthrough().nullable().optional(),fingerprint:k().min(1).optional(),unchanged:B(!0).optional()}).passthrough(),Gs=P({id:k().min(1).max(512),fingerprint:k().min(1).max(128)});P({threadId:k().min(1),knownTurns:N(Gs).max(64).optional(),truncateToolOutput:M().optional()});let Ks=P({harnessId:k().min(1),nativeSessionId:k().min(1)});P({cursor:zs,activeTurnId:k().min(1).nullable().optional(),command:P({name:k().min(1),turn:Ws}).optional(),thread:P({id:k().min(1),cwd:k(),modelProvider:k().min(1),createdAt:j(),updatedAt:j(),status:P({type:k()}).passthrough(),name:k().nullable().optional(),preview:k().optional(),codexhostImportSource:Ks.optional(),turns:N(Ws).length(0)}).passthrough(),turnsPage:P({data:N(Ws).max(5),nextCursor:k().nullable()}),configuration:P({native:P({model:k().min(1).max(1024).optional(),reasoningEffort:k().min(1).max(128).optional()}).optional(),effectiveModel:J.optional(),effectiveThinkingOptionId:Y.optional(),effectivePermissionModeId:G.optional()}),queue:P({items:N(Us),pausedReason:z([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:N(Hs)}),P({version:B(1),owner:B(`service`).optional(),pid:j().int().positive(),port:j().int().min(1).max(65535),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j(),epoch:k().uuid()}),P({epoch:k().uuid(),threadId:k().min(1),requestId:I([k(),j().int()]),result:Rs}),P({includeArchived:M().optional()}).strict(),P({threads:N(ss),ownership:N(Ls),archivedThreadIds:N(W)}).strict();let qs=k().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);P({available:M()}).strict(),P({path:k().min(1),mimeType:qs}).strict();let Js=z([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);L(`ok`,[P({ok:B(!0),text:k()}).strict(),P({ok:B(!1),error:P({code:Js}).strict()}).strict()]);let Ys=P({kind:z([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:k().min(1)}).strict(),Xs=L(`status`,[P({status:B(`not-installed`)}),P({status:B(`not-running`)}),P({status:B(`not-logged-in`)}),P({status:B(`https-disabled`)}),P({status:B(`not-serving`),command:k()}),P({status:B(`occupied`),target:k()}),P({status:B(`serving`),url:k(),funnel:M()}),P({status:B(`error`),message:k()})]);P({state:Xs,error:k().optional()}).strict();let Zs=L(`status`,[P({status:B(`on`)}),P({status:B(`off`)}),P({status:B(`invalid`),reason:k()})]),Qs=P({lan:M(),autostart:Zs}).strict(),$s=P({expiresAt:k().optional(),issuing:M(),failure:P({detail:k().optional(),retryAt:k(),paused:M()}).optional()}),ec=L(`status`,[P({status:B(`off`),reason:z([`invite`,`name-taken`,`banned`]).optional()}),P({status:B(`connecting`),reason:z([`full`,`unreachable`]).optional()}),P({status:B(`connected`),url:k(),certificate:$s}),P({status:B(`missing-certificate`),url:k(),certificate:$s}),P({status:B(`stopped`),reason:z([`replaced`,`rejected`,`unsupported-version`])})]);k().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()),k().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let tc=z([`official`,`self-hosted`]);P({secret:k().min(1),lastUsedAt:j().nullable(),networkUrls:N(Ys),directCandidates:N(Ys).optional(),tailscale:Xs,background:Qs.optional(),relay:P({state:ec,enabled:M(),kind:tc,officialHost:k(),customHost:k().optional(),officialHostname:k().optional(),customHostname:k().optional(),quotaUntil:k().optional()}).strict().optional()}).strict(),P({url:k()}).strict();let nc=F({threadId:k().min(1).max(1024),view:z([`result`,`messages`]),cursor:k().min(1).max(8192).optional(),limit:j().int().min(1).max(100).optional()}),rc=P({id:k().min(1).max(256),harnessId:k().min(1),label:k().min(1).max(512),provider:z([`openai-codex`,`xai`])}).strict(),ic=k().regex(/^[a-z][a-z0-9-]{0,47}$/),ac=P({name:ic,source:rc,importedAt:k()}).strict(),oc=L(`action`,[P({action:B(`list`)}).strict(),P({action:B(`import`),sourceId:k().min(1).max(256),name:ic,confirmed:B(!0)}).strict(),P({action:B(`reimport`),sourceId:k().min(1).max(256),name:ic,confirmed:B(!0)}).strict(),P({action:B(`remove`),name:ic,confirmed:B(!0)}).strict()]),sc=P({provider:k().min(1).max(128),type:z([`oauth`,`api_key`,`unknown`]),label:k().min(1).max(512).optional(),vendor:z([`openai-codex`,`xai`]).optional()}).strict();P({sources:N(rc),targets:N(P({harnessId:k(),providers:N(z([`openai-codex`,`xai`])),imports:N(ac),others:N(sc).default([])}).strict())}).strict(),P({targetHarnessId:k().min(1).max(128).optional(),request:oc}).strict(),P({events:M()});let cc=N(F({agent:k().min(1).max(128),section:z([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);F({entries:cc.nullable()}),F({}),F({entries:cc,initializeOnly:M().optional()});let lc=F({enabled:M(),timeoutMinutes:j().int().min(5).max(1440)});Object.freeze({enabled:!1,timeoutMinutes:30});let uc=k().regex(/^external$/u),dc=U.transform(e=>String(e)),fc=F({model:J.optional(),thinkingOptionId:Y.optional(),permissionModeId:G.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),pc=F({lastHarness:U.optional(),byHarness:R(dc,fc)}),mc=k().min(1).max(1024),hc=F({idleRelease:lc.optional(),favorites:R(dc,N(mc).max(2048)).default({}),newThread:pc.optional()});F({scope:uc,revision:j().int().nonnegative(),values:hc}),F({scope:uc.default(`external`)});let gc=L(`kind`,[F({kind:B(`idleRelease`),value:lc}),F({kind:B(`favorite`),harnessId:U,modelId:mc,enabled:M()}),F({kind:B(`favorites`),harnessId:U,modelIds:N(mc).max(2048)}),F({kind:B(`newThread`),lastHarness:U.optional(),harnessId:U.optional(),configuration:fc.optional()})]);F({scope:uc.default(`external`),operations:N(gc).min(1).max(256),initializeOnly:M().optional(),expectedRevision:j().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`})}),F({version:B(1),revision:j().int().nonnegative(),scopes:R(uc,hc)});let _c=j().finite().nonnegative(),vc=F({input:_c,output:_c,cacheRead:_c.optional(),cacheWrite:_c.optional(),cacheWrite1h:_c.optional()}),yc=k().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);F({path:k(),entries:N(F({key:k(),price:vc})),error:k().nullable()}),F({}),F({key:yc,price:vc.nullable(),previousKey:yc.optional()}),F({model:yc});let bc=F({official:M().optional(),canonicalModelId:k().min(1).optional(),provider:k().min(1).max(512),model:k().min(1).max(512),price:vc});F({price:vc.nullable(),suggestions:N(bc).max(6).optional()});let xc=[`today`,`7d`,`30d`,`90d`,`all`],X=j().int().min(0).max(2**53-1),Sc=k().regex(/^\d{4}-\d{2}-\d{2}$/u),Z=k().min(1).max(128),Q=k().min(1).max(512),Cc=k().min(1).max(4096);F({range:z(xc),timeZone:k().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:Z.optional(),model:Q.nullable().optional(),project:Cc.nullable().optional(),date:Sc.optional()});let wc=F({requests:X,inputTokens:X,cachedInputTokens:X,cacheWriteInputTokens:X,cacheKnownInputTokens:X,cacheHitCachedInputTokens:X,cacheHitInputTokens:X,outputTokens:X,reasoningOutputTokens:X,costUsd:j().finite().min(0),unpricedRequests:X,unmeteredRequests:X}),Tc=wc.shape,Ec=F({harness:Z,sessionId:k().min(1).max(512),project:Cc.nullable(),title:k().min(1).max(200).optional(),models:N(Q).max(16),firstAtMs:X,lastAtMs:X,...Tc});F({range:z(xc),from:Sc.nullable(),to:Sc,filters:F({harness:Z.nullable(),model:Q.nullable(),unknownModel:M(),project:Cc.nullable(),unknownProject:M(),date:Sc.nullable()}),reading:F({complete:M(),sources:X,read:X}),failures:N(F({harness:Z,message:k().max(2048)})).max(256),options:F({harnesses:N(Z).max(256),models:N(Q.nullable()).max(4096),projects:N(Cc.nullable()).max(4096)}),modelLabels:N(F({harness:Z,model:Q,label:Q})).max(4096).optional(),credits:N(F({harness:Z,model:Q.nullable(),credits:j().finite().min(0),reportedRequests:X,requests:X})).max(4096).optional(),totals:wc,daily:N(F({date:Sc,harness:Z,...Tc})).max(2e5),hourly:N(F({weekday:j().int().min(0).max(6),hour:j().int().min(0).max(23),...Tc})).max(168),byHarness:N(F({harness:Z,...Tc})).max(256),byModel:N(F({model:Q.nullable(),...Tc,harnessPricedRequests:X})).max(4096),byProject:N(F({project:Cc.nullable(),...Tc})).max(4096),sessions:N(Ec).max(100),recentSessions:N(Ec).max(100).optional()}),P({threadId:W}),P({discarded:M()});let Dc=L(`type`,[P({id:k().min(1),type:B(`choice`),prompt:k(),options:N(P({value:k().min(1),label:k(),description:k().optional()})).min(1),multiple:M(),allowOther:M(),optional:M()}),P({id:k().min(1),type:B(`text`),prompt:k(),multiline:M(),secret:B(!1),optional:M(),placeholder:k().optional(),prefill:k().optional()})]),Oc=P({interactionId:k().min(1),turnId:k().min(1),title:k().optional(),questions:N(Dc).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});F({threadId:k().min(1)}),P({questions:N(Oc)}),F({threadId:k().min(1),turnId:k().min(1),interactionId:k().min(1),answers:R(k(),N(k())),cancelled:M().default(!1)}),P({accepted:B(!0)});let kc=/* @__PURE__ */ new Set([`codexhostTurnChanges`,`codexhostToolOutput`]),Ac=P({path:k(),oldText:k().nullable(),newText:k()});P({sessionId:k().min(1),turn:j().int().nonnegative(),path:k().min(1).optional()}),P({diffs:N(Ac)}),F({}),F({}),P({reference:P({sessionId:k().min(1),epoch:k().min(1),turn:j().int().nonnegative(),seq:j().int().nonnegative(),callId:k().min(1),part:j().int().nonnegative(),version:k().min(1)}),length:j().int().nonnegative(),bytes:j().int().nonnegative()}),F({title:k().trim().min(1).max(200),type:z([`info`,`warning`,`danger`]),body:k().trim().min(1).max(16384)}),F({}),F({url:k().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 jc=z([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),Mc=z([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);F({threadId:k(),title:k(),harnessId:k(),state:jc,reason:Mc,inactiveMs:j().nonnegative()}),F({threadId:W,turnId:ms});let Nc=P({amount:j().finite().nonnegative(),currency:k().trim().min(1).max(8),label:k().trim().min(1).max(128).optional()}).strict(),Pc=P({email:k().trim().min(1).max(320).optional(),label:k().trim().min(1).max(256).optional(),plan:k().trim().min(1).max(128).optional(),credits:Ds.optional(),balance:Nc.optional()}).strict();function Fc(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 Ic=Fc(Pc),Lc={harnessId:U,harnessName:k().trim().min(1).max(128)},Rc=P(Lc).strict();P({}).strict(),P({sources:N(Rc).max(128)}).strict(),P({harnessId:U,refresh:M().optional()}).strict(),P({...Lc,account:Ic.nullable(),accounts:N(Ic).max(8).optional()}).strict(),P({refresh:M().optional()}).strict(),P({accounts:N(Fc(Pc.extend(Lc))).max(128)}).strict();let zc=k().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).pipe(U),Bc=zc.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Vc=k().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`),Hc=qa().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),Uc=P({en:k().max(4096),"zh-CN":k().max(4096).optional()}).strict(),Wc=P({commands:N(P({terminal:k().max(256),command:k().max(4096)}).strict()).max(8),before:Uc.optional(),after:Uc.optional(),downloads:N(P({label:k().max(128),url:Hc}).strict()).max(8).optional()}).strict(),Gc={id:zc,name:k().trim().min(1).max(128),version:k().min(1).max(128),kind:B(`usage`).optional(),iconStyle:P({vector:P({viewBox:k().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:N(P({d:k().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:z([`evenodd`,`nonzero`]).optional(),fill:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:k().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:j().min(0).max(50).optional(),paddingRatio:j().min(0).max(.25).optional()}).strict().optional(),installation:Wc.optional(),notice:Uc.optional(),launchCommand:B(!0).optional(),links:P({website:Hc.optional(),documentation:Hc.optional(),installation:Hc.optional()}).strict().optional()};P({manifestVersion:B(1),...Gc,adapterApiVersion:j().int().positive(),entry:Vc,icon:Vc.optional()}).strict();let Kc=k().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),qc=P({...Gc,icon:Kc.optional()}).strict();P({}).strict(),P({plugins:N(qc.extend({id:Bc})).max(128)}).strict(),P({version:B(1),enabled:N(zc).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]}),P({harnessId:Bc,model:J.optional(),thinkingOptionId:Y.optional(),permissionModeId:G.optional(),prewarm:B(!0).optional()}).strict();let Jc=k().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);P({harnessId:Bc}).strict().extend({path:Jc.nullable()}),P({path:Jc.nullable(),restartRequired:M()}).strict(),P({harnessId:U,action:z([`check`,`update`,`install`])}).strict();let Yc=P({currentVersion:k().min(1).max(128),latestVersion:k().min(1).max(128),updateAvailable:M(),canUpdate:M(),versionKind:z([`cli`,`application`]).optional(),manualUpdateUrl:qa().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:k().max(2048).optional(),messageCode:k().min(1).max(128).optional(),notice:fs.optional(),latestVersionKind:z([`unknown`,`tracking-branch`]).optional()}).strict();P({taskId:k().uuid()}).strict(),L(`status`,[P({taskId:k().uuid(),status:B(`running`)}).strict(),P({taskId:k().uuid(),status:B(`succeeded`),result:Yc}).strict(),P({taskId:k().uuid(),status:B(`failed`),error:P({code:j().int(),message:k().min(1).max(2048)}).strict()}).strict()]);let Xc=k().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Zc=k().trim().min(1),Qc=z([`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`]),$c=P({accountId:Xc,label:Zc.max(256),email:k().email().max(320).optional(),planType:Qc.optional()}).strict(),el=z([`ready`,`unavailable`]);P({version:B(2),currentAccountId:Xc.nullable(),phase:el,revision:j().int().nonnegative(),instanceId:Zc.max(1024).optional(),accounts:N($c).max(1)}).strict(),P({accountId:Xc,refresh:M().optional()}).strict(),P({accountId:Xc,usage:xs.nullable(),accountCredits:Ds.optional(),freshness:z([`live`,`cached`]),observedAt:k().datetime().nullable()}).strict();let tl=1e3,nl=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),rl=nl.max(1024),il=P({nativeSessionId:rl,title:nl.max(4096).nullable(),updatedAt:j().int().nonnegative().max(864e13),cwd:nl.max(16384),running:M().nullable()}).strict();P({}).strict(),P({harnesses:N(P({harnessId:Bc,name:nl.max(128)}).strict()).max(128)}).strict(),P({harnessId:Bc,query:k().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:j().int().nonnegative().safe().optional(),limit:j().int().min(1).max(tl).optional()}).strict(),P({candidates:N(il).max(tl),total:j().int().nonnegative().safe()}).strict(),P({harnessId:Bc,nativeSessionId:rl}).strict(),P({threadId:nl.max(1024).pipe(W)}).strict();let al=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),ol=rl,sl=il;P({}).strict(),P({candidates:N(sl).max(1e3)}).strict(),P({nativeSessionId:ol}).strict(),P({threadId:al.max(1024).pipe(W)}).strict(),P({threadId:W,lastTurnId:ms}).strict(),P({threadId:W}).strict();let cl=k().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();P({commands:N(P({id:cl,invocation:k().min(1).max(128),label:k().trim().min(1).max(128),description:k().trim().min(1).max(512).optional(),localizations:ds.optional(),argumentMode:z([`none`,`text`]),kind:z([`command`,`skill`]).optional()}).strict()),warnings:N(k().min(1)).optional(),source:z([`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)}),P({harnessId:U,cwd:k().min(1).optional()}).strict(),P({threadId:W}).strict(),P({threadId:W,commandId:cl,turnId:ms.optional(),arguments:ss.optional()}).strict(),P({accepted:B(!0),turnId:ms.optional()}).strict();let ll=B(`2.0`).optional(),$=yo().optional(),ul=k().min(1),dl=I([k(),j().int()]),fl=P({code:j().int(),message:k(),data:H.optional()}).catchall(H).superRefine(V([`data`]));I([P({jsonrpc:ll,id:dl,method:ul,params:H.optional(),result:$,error:$}).catchall(H).superRefine(V([`jsonrpc`,`params`,`result`,`error`])),P({jsonrpc:ll,id:$,method:ul,params:H.optional(),result:$,error:$}).catchall(H).superRefine(V([`jsonrpc`,`id`,`params`,`result`,`error`])),P({jsonrpc:ll,id:dl,method:$,params:$,result:H,error:$}).catchall(H).superRefine(V([`jsonrpc`,`method`,`params`,`error`])),P({jsonrpc:ll,id:dl,method:$,params:$,result:$,error:fl}).catchall(H).superRefine(V([`jsonrpc`,`method`,`params`,`result`]))]);let pl=k().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});F({harnessId:U,nativeSessionId:pl,locator:H.optional(),formatVersion:B(1)}).superRefine(V([`locator`])),F({harnessId:U,nativeSessionId:pl,nativeTurnKey:pl,formatVersion:B(1)}),F({harnessId:U,nativeSessionId:pl,checkpointId:pl,locator:H.optional(),formatVersion:B(1)}).superRefine(V([`locator`]));let ml=k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),hl=z([`npm`,`windows-installer`,`macos-dmg`]),gl=F({version:ml,installation:hl,phase:z([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:j().int().nonnegative(),downloadedBytes:j().int().nonnegative().optional(),totalBytes:j().int().positive().optional(),error:k().min(1).max(500).nullable(),serviceStopOutput:k().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`})});F({});let _l=k().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`);F({currentVersion:ml,installation:hl.nullable(),latestVersion:ml.nullable(),updateAvailable:M(),installationAvailable:M(),releaseNotes:k().min(1).max(2e4).nullable(),releaseNotesUrl:_l.nullable(),status:gl.nullable(),error:k().min(1).max(500).nullable()}),F({status:gl}),F({status:gl.nullable()});let vl=z([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);P({runningVersion:k().nullable(),installedVersion:k().nullable(),restartRequired:M(),remote:M(),updateSupported:M(),update:P({phase:vl,targetVersion:k().nullable(),error:k().nullable()})});let yl=P({version:k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();P({hostname:k().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),action:z([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:M().optional(),version:k().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),P({state:z([`installed`,`not-installed`])}).strict();let bl=k().min(1).max(1024),xl=P({hostId:bl,displayName:k().min(1).max(1024),source:z([`codex-managed`,`discovered`]),sshAlias:k().max(1024).nullable(),sshHost:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),autoConnect:M(),connectionAnalyticsId:k().max(1024).optional()}),Sl=F({displayName:k().min(1).max(1024),hostname:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable()});L(`action`,[F({action:B(`list`)}),F({action:B(`read-thread`),hostId:bl.refine(e=>e!==`local`),input:nc}),F({action:B(`save`),draft:Sl,previous:xl.nullable()}),F({action:B(`remove`),previous:xl}),F({action:B(`connect`),hostId:bl,enabled:M()}),F({action:B(`state`),hostId:bl}),F({action:B(`runtime`),hostId:bl}),F({action:B(`update`),hostId:bl.refine(e=>e!==`local`),version:yl.shape.version})]),I([F({result:H}),F({error:F({code:j().int(),message:k()})})]);let Cl=k().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),wl=I([k(),P({en:k()}).catchall(k())]),Tl=P({title:wl.optional(),description:wl.optional(),icon:k().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:k().optional()});P({extensions:N(P({id:Cl,name:k().min(1).max(214),version:k().min(1).max(128),format:B(`dsh`),supportedTargets:Do([B(`web`)]),enabledTargets:N(B(`web`)).max(1),source:k().min(1).max(4096),projectUrl:k().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:k(),meta:Tl.optional(),loadError:k().optional()})),loadedIds:N(Cl),safeMode:M(),storeError:k().optional()});let El=k().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}/`);P({spec:k().trim().min(1).max(4096),registry:El.optional()}).strict(),P({id:Cl,enabled:M()}).strict(),P({id:Cl}).strict(),B(1);function Dl(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 Gi(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:qi(t,`input`,e.processors),output:qi(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function E(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 E(r.element,n);if(r.type===`set`)return E(r.valueType,n);if(r.type===`lazy`)return E(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 E(r.innerType,n);if(r.type===`intersection`)return E(r.left,n)||E(r.right,n);if(r.type===`record`||r.type===`map`)return E(r.keyType,n)||E(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:E(r.in,n)||E(r.out,n);if(r.type===`object`){for(let e in r.shape)if(E(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(E(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(E(e,n))return!0;return!!(r.rest&&E(r.rest,n))}return!1}let Ki=(e,t={})=>n=>{let r=Ui({...n,processors:t});return T(e,r),Wi(r,e),Gi(r,e)},qi=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Ui({...i??{},target:a,io:t,processors:n});return T(e,o),Wi(o,e),Gi(o,e)},Ji={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Yi=(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=Ji[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}))])}},Xi=(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)},Zi=(e,t,n,r)=>{n.type=`boolean`},Qi=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},$i=(e,t,n,r)=>{n.not={}},ea=(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},ta=(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}},na=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},ra=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},ia=(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=T(a.element,t,{...r,path:[...r.path,`items`]})},aa=(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]=T(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=T(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},oa=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>T(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},sa=(e,t,n,r)=>{let i=e._zod.def,a=T(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=T(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]]},ca=(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)=>T(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?T(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)},la=(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=T(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=T(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=T(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)}},ua=(e,t,n,r)=>{let i=e._zod.def,a=T(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`}]},da=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},fa=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},pa=(e,t,n,r)=>{let i=e._zod.def;T(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)))},ma=(e,t,n,r)=>{let i=e._zod.def;T(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},ha=(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;T(o,t,r);let s=t.seen.get(e);s.ref=o},ga=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},_a=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},va=(e,t,n,r)=>{let i=e._zod.innerType;T(i,t,r);let a=t.seen.get(e);a.ref=i},ya=/*@__PURE__*/ h(`ZodISODateTime`,(e,t)=>{An.init(e,t),A.init(e,t)});function ba(e){return/* @__PURE__ */ ci(ya,e)}let xa=/*@__PURE__*/ h(`ZodISODate`,(e,t)=>{jn.init(e,t),A.init(e,t)});function Sa(e){return/* @__PURE__ */ li(xa,e)}let Ca=/*@__PURE__*/ h(`ZodISOTime`,(e,t)=>{Mn.init(e,t),A.init(e,t)});function wa(e){return/* @__PURE__ */ ui(Ca,e)}let Ta=/*@__PURE__*/ h(`ZodISODuration`,(e,t)=>{Nn.init(e,t),A.init(e,t)});function Ea(e){return/* @__PURE__ */ di(Ta,e)}let D=/*@__PURE__*/ h(`ZodError`,(e,t)=>{it.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>st(e,t)},flatten:{value:t=>ot(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}),Da=/* @__PURE__ */ ct(D),Oa=/* @__PURE__ */ lt(D),ka=/* @__PURE__ */ ut(D),Aa=/* @__PURE__ */ ft(D),ja=/* @__PURE__ */ mt(D),Ma=/* @__PURE__ */ ht(D),Na=/* @__PURE__ */ gt(D),Pa=/* @__PURE__ */ _t(D),Fa=/* @__PURE__ */ vt(D),Ia=/* @__PURE__ */ yt(D),La=/* @__PURE__ */ bt(D),Ra=/* @__PURE__ */ xt(D),za=/* @__PURE__ */ new WeakMap;function Ba(e,t,n){let r=Object.getPrototypeOf(e),i=za.get(r);if(i||(i=/* @__PURE__ */ new Set,za.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 O=/*@__PURE__*/ h(`ZodType`,(e,t)=>(C.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:qi(e,`input`),output:qi(e,`output`)}}),e.toJSONSchema=Ki(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Da(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ka(e,t,n),e.parseAsync=async(t,n)=>Oa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Aa(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>ja(e,t,n),e.decode=(t,n)=>Ma(e,t,n),e.encodeAsync=async(t,n)=>Na(e,t,n),e.decodeAsync=async(t,n)=>Pa(e,t,n),e.safeEncode=(t,n)=>Fa(e,t,n),e.safeDecode=(t,n)=>Ia(e,t,n),e.safeEncodeAsync=async(t,n)=>La(e,t,n),e.safeDecodeAsync=async(t,n)=>Ra(e,t,n),Ba(e,`ZodType`,{check(...e){let t=this.def;return this.clone(v(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 He(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(ts(e,t))},superRefine(e,t){return this.check(ns(e,t))},overwrite(e){return this.check(/* @__PURE__ */ Mi(e))},optional(){return Po(this)},exactOptional(){return Io(this)},nullable(){return Ro(this)},nullish(){return Po(Ro(this))},nonoptional(e){return Wo(this,e)},array(){return N(this)},or(e){return I([this,e])},and(e){return To(this,e)},transform(e){return Jo(this,Mo(e))},default(e){return Bo(this,e)},prefault(e){return Ho(this,e)},catch(e){return Ko(this,e)},pipe(e){return Jo(this,e)},readonly(){return Xo(this)},describe(e){let t=this.clone();return Rr.add(t,{description:e}),t},meta(...e){if(e.length===0)return Rr.get(this);let t=this.clone();return Rr.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 Rr.get(e)?.description},configurable:!0}),e)),Va=/*@__PURE__*/ h(`_ZodString`,(e,t)=>{vn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ba(e,`_ZodString`,{regex(...e){return this.check(/* @__PURE__ */ Ei(...e))},includes(...e){return this.check(/* @__PURE__ */ ki(...e))},startsWith(...e){return this.check(/* @__PURE__ */ Ai(...e))},endsWith(...e){return this.check(/* @__PURE__ */ ji(...e))},min(...e){return this.check(/* @__PURE__ */ wi(...e))},max(...e){return this.check(/* @__PURE__ */ Ci(...e))},length(...e){return this.check(/* @__PURE__ */ Ti(...e))},nonempty(...e){return this.check(/* @__PURE__ */ wi(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ Di(e))},uppercase(e){return this.check(/* @__PURE__ */ Oi(e))},trim(){return this.check(/* @__PURE__ */ Pi())},normalize(...e){return this.check(/* @__PURE__ */ Ni(...e))},toLowerCase(){return this.check(/* @__PURE__ */ Fi())},toUpperCase(){return this.check(/* @__PURE__ */ Ii())},slugify(){return this.check(/* @__PURE__ */ Li())}})}),Ha=/*@__PURE__*/ h(`ZodString`,(e,t)=>{vn.init(e,t),Va.init(e,t),e.email=t=>e.check(/* @__PURE__ */ Br(Ua,t)),e.url=t=>e.check(/* @__PURE__ */ Kr(Ka,t)),e.jwt=t=>e.check(/* @__PURE__ */ si(co,t)),e.emoji=t=>e.check(/* @__PURE__ */ qr(Ja,t)),e.guid=t=>e.check(/* @__PURE__ */ Vr(Wa,t)),e.uuid=t=>e.check(/* @__PURE__ */ Hr(Ga,t)),e.uuidv4=t=>e.check(/* @__PURE__ */ Ur(Ga,t)),e.uuidv6=t=>e.check(/* @__PURE__ */ Wr(Ga,t)),e.uuidv7=t=>e.check(/* @__PURE__ */ Gr(Ga,t)),e.nanoid=t=>e.check(/* @__PURE__ */ Jr(Ya,t)),e.guid=t=>e.check(/* @__PURE__ */ Vr(Wa,t)),e.cuid=t=>e.check(/* @__PURE__ */ Yr(Xa,t)),e.cuid2=t=>e.check(/* @__PURE__ */ Xr(Za,t)),e.ulid=t=>e.check(/* @__PURE__ */ Zr(Qa,t)),e.base64=t=>e.check(/* @__PURE__ */ ii(ao,t)),e.base64url=t=>e.check(/* @__PURE__ */ ai(oo,t)),e.xid=t=>e.check(/* @__PURE__ */ Qr($a,t)),e.ksuid=t=>e.check(/* @__PURE__ */ $r(eo,t)),e.ipv4=t=>e.check(/* @__PURE__ */ ei(to,t)),e.ipv6=t=>e.check(/* @__PURE__ */ ti(no,t)),e.cidrv4=t=>e.check(/* @__PURE__ */ ni(ro,t)),e.cidrv6=t=>e.check(/* @__PURE__ */ ri(io,t)),e.e164=t=>e.check(/* @__PURE__ */ oi(so,t)),e.datetime=t=>e.check(ba(t)),e.date=t=>e.check(Sa(t)),e.time=t=>e.check(wa(t)),e.duration=t=>e.check(Ea(t))});function k(e){return/* @__PURE__ */ zr(Ha,e)}let A=/*@__PURE__*/ h(`ZodStringFormat`,(e,t)=>{w.init(e,t),Va.init(e,t)}),Ua=/*@__PURE__*/ h(`ZodEmail`,(e,t)=>{xn.init(e,t),A.init(e,t)}),Wa=/*@__PURE__*/ h(`ZodGUID`,(e,t)=>{yn.init(e,t),A.init(e,t)}),Ga=/*@__PURE__*/ h(`ZodUUID`,(e,t)=>{bn.init(e,t),A.init(e,t)}),Ka=/*@__PURE__*/ h(`ZodURL`,(e,t)=>{Sn.init(e,t),A.init(e,t)});function qa(e){return/* @__PURE__ */ Kr(Ka,e)}let Ja=/*@__PURE__*/ h(`ZodEmoji`,(e,t)=>{Cn.init(e,t),A.init(e,t)}),Ya=/*@__PURE__*/ h(`ZodNanoID`,(e,t)=>{wn.init(e,t),A.init(e,t)}),Xa=/*@__PURE__*/ h(`ZodCUID`,(e,t)=>{Tn.init(e,t),A.init(e,t)}),Za=/*@__PURE__*/ h(`ZodCUID2`,(e,t)=>{En.init(e,t),A.init(e,t)}),Qa=/*@__PURE__*/ h(`ZodULID`,(e,t)=>{Dn.init(e,t),A.init(e,t)}),$a=/*@__PURE__*/ h(`ZodXID`,(e,t)=>{On.init(e,t),A.init(e,t)}),eo=/*@__PURE__*/ h(`ZodKSUID`,(e,t)=>{kn.init(e,t),A.init(e,t)}),to=/*@__PURE__*/ h(`ZodIPv4`,(e,t)=>{Pn.init(e,t),A.init(e,t)}),no=/*@__PURE__*/ h(`ZodIPv6`,(e,t)=>{Fn.init(e,t),A.init(e,t)}),ro=/*@__PURE__*/ h(`ZodCIDRv4`,(e,t)=>{In.init(e,t),A.init(e,t)}),io=/*@__PURE__*/ h(`ZodCIDRv6`,(e,t)=>{Ln.init(e,t),A.init(e,t)}),ao=/*@__PURE__*/ h(`ZodBase64`,(e,t)=>{zn.init(e,t),A.init(e,t)}),oo=/*@__PURE__*/ h(`ZodBase64URL`,(e,t)=>{Vn.init(e,t),A.init(e,t)}),so=/*@__PURE__*/ h(`ZodE164`,(e,t)=>{Hn.init(e,t),A.init(e,t)}),co=/*@__PURE__*/ h(`ZodJWT`,(e,t)=>{Wn.init(e,t),A.init(e,t)}),lo=/*@__PURE__*/ h(`ZodNumber`,(e,t)=>{Gn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r),Ba(e,`ZodNumber`,{gt(e,t){return this.check(/* @__PURE__ */ bi(e,t))},gte(e,t){return this.check(/* @__PURE__ */ xi(e,t))},min(e,t){return this.check(/* @__PURE__ */ xi(e,t))},lt(e,t){return this.check(/* @__PURE__ */ vi(e,t))},lte(e,t){return this.check(/* @__PURE__ */ yi(e,t))},max(e,t){return this.check(/* @__PURE__ */ yi(e,t))},int(e){return this.check(fo(e))},safe(e){return this.check(fo(e))},positive(e){return this.check(/* @__PURE__ */ bi(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ xi(0,e))},negative(e){return this.check(/* @__PURE__ */ vi(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ yi(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Si(e,t))},step(e,t){return this.check(/* @__PURE__ */ Si(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 j(e){return/* @__PURE__ */ fi(lo,e)}let uo=/*@__PURE__*/ h(`ZodNumberFormat`,(e,t)=>{Kn.init(e,t),lo.init(e,t)});function fo(e){return/* @__PURE__ */ pi(uo,e)}let po=/*@__PURE__*/ h(`ZodBoolean`,(e,t)=>{qn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r)});function M(e){return/* @__PURE__ */ mi(po,e)}let mo=/*@__PURE__*/ h(`ZodNull`,(e,t)=>{Jn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r)});function ho(e){return/* @__PURE__ */ hi(mo,e)}let go=/*@__PURE__*/ h(`ZodUnknown`,(e,t)=>{Yn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function _o(){return/* @__PURE__ */ gi(go)}let vo=/*@__PURE__*/ h(`ZodNever`,(e,t)=>{Xn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r)});function yo(e){return/* @__PURE__ */ _i(vo,e)}let bo=/*@__PURE__*/ h(`ZodArray`,(e,t)=>{Qn.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ia(e,t,n,r),e.element=t.element,Ba(e,`ZodArray`,{min(e,t){return this.check(/* @__PURE__ */ wi(e,t))},nonempty(e){return this.check(/* @__PURE__ */ wi(1,e))},max(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},length(e,t){return this.check(/* @__PURE__ */ Ti(e,t))},unwrap(){return this.element}})});function N(e,t){return/* @__PURE__ */ Ri(bo,e,t)}let xo=/*@__PURE__*/ h(`ZodObject`,(e,t)=>{rr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aa(e,t,n,r),_(e,`shape`,()=>t.shape),Ba(e,`ZodObject`,{keyof(){return z(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:_o()})},loose(){return this.clone({...this._zod.def,catchall:_o()})},strict(){return this.clone({...this._zod.def,catchall:yo()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return qe(this,e)},safeExtend(e){return Je(this,e)},merge(e){return Ye(this,e)},pick(e){return Ge(this,e)},omit(e){return Ke(this,e)},partial(...e){return Xe(No,this,e[0])},required(...e){return Ze(Uo,this,e[0])}})});function P(e,t){let n={type:`object`,shape:e??{},...y(t)};return new xo(n)}function F(e,t){return new xo({type:`object`,shape:e,catchall:yo(),...y(t)})}let So=/*@__PURE__*/ h(`ZodUnion`,(e,t)=>{ar.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),e.options=t.options});function I(e,t){return new So({type:`union`,options:e,...y(t)})}let Co=/*@__PURE__*/ h(`ZodDiscriminatedUnion`,(e,t)=>{So.init(e,t),or.init(e,t)});function L(e,t,n){return new Co({type:`union`,options:t,discriminator:e,...y(n)})}let wo=/*@__PURE__*/ h(`ZodIntersection`,(e,t)=>{sr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sa(e,t,n,r)});function To(e,t){return new wo({type:`intersection`,left:e,right:t})}let Eo=/*@__PURE__*/ h(`ZodTuple`,(e,t)=>{ur.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ca(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function Do(e,t,n){let r=t instanceof C;return new Eo({type:`tuple`,items:e,rest:r?t:null,...y(r?n:t)})}let Oo=/*@__PURE__*/ h(`ZodRecord`,(e,t)=>{mr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>la(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function R(e,t,n){return!t||!t._zod?new Oo({type:`record`,keyType:k(),valueType:e,...y(t)}):new Oo({type:`record`,keyType:e,valueType:t,...y(n)})}let ko=/*@__PURE__*/ h(`ZodEnum`,(e,t)=>{hr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(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 ko({...t,checks:[],...y(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 ko({...t,checks:[],...y(r),entries:i})}});function z(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ko({type:`enum`,entries:n,...y(t)})}let Ao=/*@__PURE__*/ h(`ZodLiteral`,(e,t)=>{gr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(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 B(e,t){return new Ao({type:`literal`,values:Array.isArray(e)?e:[e],...y(t)})}let jo=/*@__PURE__*/ h(`ZodTransform`,(e,t)=>{_r.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ra(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(nt(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(nt(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 Mo(e){return new jo({type:`transform`,transform:e})}let No=/*@__PURE__*/ h(`ZodOptional`,(e,t)=>{yr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Po(e){return new No({type:`optional`,innerType:e})}let Fo=/*@__PURE__*/ h(`ZodExactOptional`,(e,t)=>{br.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Fo({type:`optional`,innerType:e})}let Lo=/*@__PURE__*/ h(`ZodNullable`,(e,t)=>{xr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ua(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ro(e){return new Lo({type:`nullable`,innerType:e})}let zo=/*@__PURE__*/ h(`ZodDefault`,(e,t)=>{Sr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bo(e,t){return new zo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}let Vo=/*@__PURE__*/ h(`ZodPrefault`,(e,t)=>{wr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ho(e,t){return new Vo({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ze(t)}})}let Uo=/*@__PURE__*/ h(`ZodNonOptional`,(e,t)=>{Tr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>da(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wo(e,t){return new Uo({type:`nonoptional`,innerType:e,...y(t)})}let Go=/*@__PURE__*/ h(`ZodCatch`,(e,t)=>{Dr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ma(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ko(e,t){return new Go({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let qo=/*@__PURE__*/ h(`ZodPipe`,(e,t)=>{Or.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ha(e,t,n,r),e.in=t.in,e.out=t.out});function Jo(e,t){return new qo({type:`pipe`,in:e,out:t})}let Yo=/*@__PURE__*/ h(`ZodReadonly`,(e,t)=>{Ar.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ga(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xo(e){return new Yo({type:`readonly`,innerType:e})}let Zo=/*@__PURE__*/ h(`ZodLazy`,(e,t)=>{Mr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>va(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Qo(e){return new Zo({type:`lazy`,getter:e})}let $o=/*@__PURE__*/ h(`ZodCustom`,(e,t)=>{Nr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>na(e,t,n,r)});function es(e,t){return/* @__PURE__ */ zi($o,e??(()=>!0),t)}function ts(e,t={}){return/* @__PURE__ */ Bi($o,e,t)}function ns(e,t){return/* @__PURE__ */ Vi(e,t)}function V(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 rs=I([k(),j(),M(),ho()]);function is(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 as=es(is,{message:`JSON value must not contain circular references`}),os=Qo(()=>I([rs,N(os),R(k(),os)])),H=as.pipe(os);as.pipe(N(os));let ss=as.pipe(R(k(),os)),cs=F({code:k().min(1),message:k().min(1),retryable:M(),diagnostic:k().min(1).optional(),stage:k().min(1).optional(),durationMs:j().int().nonnegative().optional(),stderrTail:k().min(1).optional()}).superRefine(V([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),ls=k().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),us=e=>k().min(1).max(e).refine(e=>e.trim().length>0),ds=R(ls,P({label:us(256).optional(),description:us(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),fs=R(ls,us(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),ps=k().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),U=ps.brand(),W=ps.brand(),ms=ps.brand();ps.brand(),ps.brand();let hs=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),G=hs.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),gs=P({modes:N(P({id:G,label:hs.max(256),description:hs.max(1024).optional(),dangerous:M().optional(),localizations:ds.optional()}).strict()).min(1).max(32),defaultModeId:G}).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`]})});P({threadId:W,permissionModeId:G}).strict();let K=j().int().safe().nonnegative(),_s=j().finite().nonnegative(),vs=j().finite().min(0).max(100),ys=P({value:_s,turnId:k().min(1).max(1024),at:K}).strict();P({outputTokensPerSecond:ys.optional(),timeToFirstOutputMs:ys.extend({value:K}).optional()}).strict();let bs=e=>fs.refine(t=>Object.values(t).every(t=>t.length<=e)),xs=P({composerIndicators:N(P({kind:B(`countdown`),id:k().min(1).max(64),expiresAtUnix:K,label:bs(256).optional(),tooltip:bs(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:K.optional(),cachedInputTokens:K.optional(),cacheWriteInputTokens:K.optional(),outputTokens:K.optional(),outputTokensPerSecond:_s.optional(),apiOutputTokensPerSecond:_s.optional(),reasoningOutputTokens:K.optional(),totalTokens:K.optional(),totalCostUsd:_s.optional(),totalCredits:_s.optional(),contextUsagePercent:_s.optional(),cacheHitRatePercent:vs.optional(),contextWindowTokens:K.optional(),contextUsedTokens:K.optional(),planFiveHourUsedPercent:vs.optional(),planFiveHourResetsAtUnix:K.optional(),planSevenDayUsedPercent:vs.optional(),planSevenDayResetsAtUnix:K.optional(),sessionCacheHitRatePercent:vs.optional(),timeToFirstOutputMs:K.optional(),costSource:z([`publicPrice`,`native`]).optional(),unpricedModels:N(k().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`]})}),Ss=j().finite().min(0).max(100),Cs=z([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),ws=P({id:k().min(1).max(256),label:k().min(1).max(256),localizations:ds.optional()}).strict(),Ts=P({product:k().min(1),periodType:Cs.optional(),scope:ws.optional(),localizations:ds.optional(),used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),usagePercent:Ss,resetsAt:k().min(1).optional()}).strict(),Es=P({availableCount:j().int().safe().positive(),nextExpiresAt:k().min(1).optional(),expiresAt:N(k().min(1)).min(1).max(32).optional()}).strict(),Ds=P({used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),label:k().min(1).optional(),scope:ws.optional(),localizations:ds.optional(),usedPercent:Ss,resetsAt:k().min(1).optional(),periodType:Cs,productUsage:N(Ts).min(1).optional(),resetCredits:Es.optional()}).strict();P({threadId:W,refresh:B(`exact`).optional()}).strict(),P({threadId:W,usage:xs.nullable(),accountCredits:Ds.optional(),accountCreditsSupported:M().optional()}).strict();let q=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),J=P({id:q.max(512).regex(/^[A-Za-z0-9._~-]+$/u,`Model Ref must use transport-safe opaque characters`).brand()}).strict(),Y=q.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Os=q.max(256),ks=P({id:Y,label:q.max(256)}).strict(),As=P({ref:J,label:q.max(256),resolvedModelLabel:Os.optional(),fastModel:J.optional(),supportedThinkingOptionIds:N(Y).optional()}).strict(),js=N(ks).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)}),Ms=P({models:N(As),defaultModel:J.optional(),thinkingOptions:js,defaultThinkingOptionId:Y.optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set,r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.has(a.ref.id)&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.add(a.ref.id),a.fastModel&&((n.has(a.fastModel.id)||e.models.some(e=>e.ref.id===a.fastModel?.id))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.add(a.fastModel.id));let o=/* @__PURE__ */ new Set;for(let[e,n]of(a.supportedThinkingOptionIds??[]).entries())o.has(n)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,e]}),o.add(n),r.has(n)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,e]})}e.defaultModel&&!n.has(e.defaultModel.id)&&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`]})}),Ns=P({fork:M(),forkAcrossCwd:M(),rollbackLastTurn:M()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Ps=z([`live`,`atCreate`]),Fs=P({configuration:P({selectModel:M(),selectThinkingOption:M(),selectPermissionMode:M(),permissionModeScope:Ps.default(`live`)}).strict(),history:Ns,subagents:P({observe:M(),readTranscript:M()}).strict().optional(),autonomousTurns:P({observe:M()}).strict().optional(),steer:M().optional()}).strict();P({effectiveModel:J.optional(),resolvedModelLabel:Os.optional(),effectiveThinkingOptionId:Y.optional(),availableThinkingOptions:js.optional(),effectivePermissionModeId:G.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 Is=P({open:B(!0)}).strict();I([P({status:B(`ready`),catalog:Ms,permissionModes:gs.optional(),capabilities:Fs,webUi:Is.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`]})}),P({status:z([`notInstalled`,`unavailable`,`error`]),error:cs}).strict()]),P({harnessId:U,cwd:q.max(16384).optional(),refresh:M().optional(),purpose:B(`availability`).optional()}).strict(),P({harnessId:U}).strict(),P({}).strict(),P({threadId:W,model:J}).strict(),P({threadId:W,thinkingOptionId:Y}).strict(),P({threadId:W,includeReferenceCapability:M().optional()}).strict(),L(`owner`,[P({owner:B(`codex`),locked:M(),effectiveModel:J.optional(),resolvedModelLabel:Os.optional(),effectiveThinkingOptionId:Y.optional(),effectivePermissionModeId:G.optional(),history:Ns.optional(),supportsThreadReferences:B(!0).optional()}).strict(),P({owner:B(`external`),harnessId:q.max(256),transportModelId:q.max(1024),effectiveModel:J.optional(),resolvedModelLabel:Os.optional(),effectiveThinkingOptionId:Y.optional(),availableThinkingOptions:js.optional(),effectivePermissionModeId:G.optional(),history:Ns,usage:xs.optional(),locked:B(!0)}).strict()]),P({threadIds:N(W).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 Ls=L(`owner`,[P({threadId:W,owner:B(`codex`)}).strict(),P({threadId:W,owner:B(`external`),harnessId:k().max(256).pipe(U)}).strict()]);P({threads:N(Ls).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)}),P({threadId:W,text:k().optional()}).strict(),P({kind:B(`application`),value:k().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),xe}}).pipe(P({expectedTurnId:ms,clientUserMessageId:k().min(1),delivery:z([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),z([`activeTurn`,`newTurn`]),P({delivery:z([`official`,`activeTurn`,`newTurn`])}).strict(),P({threadIds:N(k().min(1))}).strict(),P({threadId:k().min(1).max(1024),pinned:M()}).strict(),P({prompt:k().max(16384).optional()}).strict(),P({projects:N(P({id:k(),name:k(),rootPaths:N(k())})),assignments:R(k(),k()),projectless:N(k()),pinned:N(k())});let Rs=R(k(),_o()),zs=P({epoch:k().uuid(),sequence:j().int().nonnegative()});L(`type`,[P({type:B(`display-settings-changed`),cursor:zs}),P({type:B(`preferences-changed`),cursor:zs,revision:j().int().nonnegative()}),P({type:B(`hello`),version:B(1),cursor:zs,reset:M()}),P({type:B(`changed`),cursor:zs,threadId:k().min(1),method:k().min(1)})]);let Bs=L(`type`,[P({type:B(`text`),id:k(),prompt:k(),secret:M().optional(),optional:M().optional()}),P({type:B(`choice`),id:k(),prompt:k(),multiple:M(),allowOther:M(),optional:M().optional(),options:N(P({value:k(),label:k(),description:k().optional()}))})]),Vs=L(`type`,[P({type:B(`approval`),title:k(),description:k().optional(),subject:_o().optional(),actions:N(P({id:k(),label:k(),effect:k()}))}),P({type:B(`question`),title:k().optional(),questions:N(Bs)})]),Hs=P({requestId:I([k(),j().int()]),threadId:k(),kind:z([`approval`,`question`]),interaction:Vs,request:Rs}),Us=P({id:k().min(1),clientUserMessageId:k().min(1),input:N(Rs),presentationInput:N(Rs).nullable().optional()}).passthrough();P({fields:N(P({path:N(I([k(),j().int().nonnegative()])),originalLength:j().int().nonnegative()}))});let Ws=P({id:k().min(1),status:k().min(1),items:N(P({id:k().min(1),type:k().min(1)}).passthrough()),codexhostFileOperations:N(P({beforeItemId:k().nullable(),item:P({id:k().min(1),type:k().min(1)}).passthrough()})).optional(),error:P({message:k().optional()}).passthrough().nullable().optional(),fingerprint:k().min(1).optional(),unchanged:B(!0).optional()}).passthrough(),Gs=P({id:k().min(1).max(512),fingerprint:k().min(1).max(128)});P({threadId:k().min(1),knownTurns:N(Gs).max(64).optional(),truncateToolOutput:M().optional()});let Ks=P({harnessId:k().min(1),nativeSessionId:k().min(1)});P({cursor:zs,activeTurnId:k().min(1).nullable().optional(),command:P({name:k().min(1),turn:Ws}).optional(),thread:P({id:k().min(1),cwd:k(),modelProvider:k().min(1),createdAt:j(),updatedAt:j(),status:P({type:k()}).passthrough(),name:k().nullable().optional(),preview:k().optional(),codexhostImportSource:Ks.optional(),turns:N(Ws).length(0)}).passthrough(),turnsPage:P({data:N(Ws).max(5),nextCursor:k().nullable()}),configuration:P({native:P({model:k().min(1).max(1024).optional(),reasoningEffort:k().min(1).max(128).optional()}).optional(),effectiveModel:J.optional(),effectiveThinkingOptionId:Y.optional(),effectivePermissionModeId:G.optional()}),queue:P({items:N(Us),pausedReason:z([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:N(Hs)}),P({version:B(1),owner:B(`service`).optional(),pid:j().int().positive(),port:j().int().min(1).max(65535),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j(),epoch:k().uuid()}),P({epoch:k().uuid(),threadId:k().min(1),requestId:I([k(),j().int()]),result:Rs}),P({includeArchived:M().optional(),officialCursor:P({live:k().nullable(),archived:k().nullable().optional()}).strict().optional()}).strict(),P({threads:N(ss),ownership:N(Ls),archivedThreadIds:N(W),officialCursor:P({live:k().nullable(),archived:k().nullable().optional()}).strict().optional()}).strict();let qs=k().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);P({available:M()}).strict(),P({path:k().min(1),mimeType:qs}).strict();let Js=z([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);L(`ok`,[P({ok:B(!0),text:k()}).strict(),P({ok:B(!1),error:P({code:Js}).strict()}).strict()]);let Ys=P({kind:z([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:k().min(1)}).strict(),Xs=L(`status`,[P({status:B(`not-installed`)}),P({status:B(`not-running`)}),P({status:B(`not-logged-in`)}),P({status:B(`https-disabled`)}),P({status:B(`not-serving`),command:k()}),P({status:B(`occupied`),target:k()}),P({status:B(`serving`),url:k(),funnel:M()}),P({status:B(`error`),message:k()})]);P({state:Xs,error:k().optional()}).strict();let Zs=L(`status`,[P({status:B(`on`)}),P({status:B(`off`)}),P({status:B(`invalid`),reason:k()})]),Qs=P({lan:M(),autostart:Zs}).strict(),$s=P({expiresAt:k().optional(),issuing:M(),failure:P({detail:k().optional(),retryAt:k(),paused:M()}).optional()}),ec=L(`status`,[P({status:B(`off`),reason:z([`invite`,`name-taken`,`banned`]).optional()}),P({status:B(`connecting`),reason:z([`full`,`unreachable`]).optional()}),P({status:B(`connected`),url:k(),certificate:$s}),P({status:B(`missing-certificate`),url:k(),certificate:$s}),P({status:B(`stopped`),reason:z([`replaced`,`rejected`,`unsupported-version`])})]);k().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()),k().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let tc=z([`official`,`self-hosted`]);P({secret:k().min(1),lastUsedAt:j().nullable(),networkUrls:N(Ys),directCandidates:N(Ys).optional(),tailscale:Xs,background:Qs.optional(),relay:P({state:ec,enabled:M(),kind:tc,officialHost:k(),customHost:k().optional(),officialHostname:k().optional(),customHostname:k().optional(),quotaUntil:k().optional()}).strict().optional()}).strict(),P({url:k()}).strict();let nc=F({threadId:k().min(1).max(1024),view:z([`result`,`messages`]),cursor:k().min(1).max(8192).optional(),limit:j().int().min(1).max(100).optional()}),rc=P({id:k().min(1).max(256),harnessId:k().min(1),label:k().min(1).max(512),provider:z([`openai-codex`,`xai`])}).strict(),ic=k().regex(/^[a-z][a-z0-9-]{0,47}$/),ac=P({name:ic,source:rc,importedAt:k()}).strict(),oc=L(`action`,[P({action:B(`list`)}).strict(),P({action:B(`import`),sourceId:k().min(1).max(256),name:ic,confirmed:B(!0)}).strict(),P({action:B(`reimport`),sourceId:k().min(1).max(256),name:ic,confirmed:B(!0)}).strict(),P({action:B(`remove`),name:ic,confirmed:B(!0)}).strict()]),sc=P({provider:k().min(1).max(128),type:z([`oauth`,`api_key`,`unknown`]),label:k().min(1).max(512).optional(),vendor:z([`openai-codex`,`xai`]).optional()}).strict();P({sources:N(rc),targets:N(P({harnessId:k(),providers:N(z([`openai-codex`,`xai`])),imports:N(ac),others:N(sc).default([])}).strict())}).strict(),P({targetHarnessId:k().min(1).max(128).optional(),request:oc}).strict(),P({events:M()});let cc=N(F({agent:k().min(1).max(128),section:z([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);F({entries:cc.nullable()}),F({}),F({entries:cc,initializeOnly:M().optional()});let lc=F({enabled:M(),timeoutMinutes:j().int().min(5).max(1440)});Object.freeze({enabled:!1,timeoutMinutes:10});let uc=k().regex(/^external$/u),dc=U.transform(e=>String(e)),fc=F({model:J.optional(),thinkingOptionId:Y.optional(),permissionModeId:G.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),pc=F({lastHarness:U.optional(),byHarness:R(dc,fc)}),mc=k().min(1).max(1024),hc=F({idleRelease:lc.optional(),favorites:R(dc,N(mc).max(2048)).default({}),newThread:pc.optional()});F({scope:uc,revision:j().int().nonnegative(),values:hc}),F({scope:uc.default(`external`)});let gc=L(`kind`,[F({kind:B(`idleRelease`),value:lc}),F({kind:B(`favorite`),harnessId:U,modelId:mc,enabled:M()}),F({kind:B(`favorites`),harnessId:U,modelIds:N(mc).max(2048)}),F({kind:B(`newThread`),lastHarness:U.optional(),harnessId:U.optional(),configuration:fc.optional()})]);F({scope:uc.default(`external`),operations:N(gc).min(1).max(256),initializeOnly:M().optional(),expectedRevision:j().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`})}),F({version:B(1),revision:j().int().nonnegative(),scopes:R(uc,hc)});let _c=j().finite().nonnegative(),vc=F({input:_c,output:_c,cacheRead:_c.optional(),cacheWrite:_c.optional(),cacheWrite1h:_c.optional()}),yc=k().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);F({path:k(),entries:N(F({key:k(),price:vc})),error:k().nullable()}),F({}),F({key:yc,price:vc.nullable(),previousKey:yc.optional()}),F({model:yc});let bc=F({official:M().optional(),canonicalModelId:k().min(1).optional(),provider:k().min(1).max(512),model:k().min(1).max(512),price:vc});F({price:vc.nullable(),suggestions:N(bc).max(6).optional()});let xc=[`today`,`7d`,`30d`,`90d`,`all`],X=j().int().min(0).max(2**53-1),Sc=k().regex(/^\d{4}-\d{2}-\d{2}$/u),Z=k().min(1).max(128),Q=k().min(1).max(512),Cc=k().min(1).max(4096);F({range:z(xc),timeZone:k().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:Z.optional(),model:Q.nullable().optional(),project:Cc.nullable().optional(),date:Sc.optional()});let wc=F({requests:X,inputTokens:X,cachedInputTokens:X,cacheWriteInputTokens:X,cacheKnownInputTokens:X,cacheHitCachedInputTokens:X,cacheHitInputTokens:X,outputTokens:X,reasoningOutputTokens:X,costUsd:j().finite().min(0),unpricedRequests:X,unmeteredRequests:X}),Tc=wc.shape,Ec=F({harness:Z,sessionId:k().min(1).max(512),project:Cc.nullable(),title:k().min(1).max(200).optional(),models:N(Q).max(16),firstAtMs:X,lastAtMs:X,...Tc});F({range:z(xc),from:Sc.nullable(),to:Sc,filters:F({harness:Z.nullable(),model:Q.nullable(),unknownModel:M(),project:Cc.nullable(),unknownProject:M(),date:Sc.nullable()}),reading:F({complete:M(),sources:X,read:X}),failures:N(F({harness:Z,message:k().max(2048)})).max(256),options:F({harnesses:N(Z).max(256),models:N(Q.nullable()).max(4096),projects:N(Cc.nullable()).max(4096)}),modelLabels:N(F({harness:Z,model:Q,label:Q})).max(4096).optional(),credits:N(F({harness:Z,model:Q.nullable(),credits:j().finite().min(0),reportedRequests:X,requests:X})).max(4096).optional(),totals:wc,daily:N(F({date:Sc,harness:Z,...Tc})).max(2e5),hourly:N(F({weekday:j().int().min(0).max(6),hour:j().int().min(0).max(23),...Tc})).max(168),byHarness:N(F({harness:Z,...Tc})).max(256),byModel:N(F({model:Q.nullable(),...Tc,harnessPricedRequests:X})).max(4096),byProject:N(F({project:Cc.nullable(),...Tc})).max(4096),sessions:N(Ec).max(100),recentSessions:N(Ec).max(100).optional()}),P({threadId:W}),P({discarded:M()});let Dc=L(`type`,[P({id:k().min(1),type:B(`choice`),prompt:k(),options:N(P({value:k().min(1),label:k(),description:k().optional()})).min(1),multiple:M(),allowOther:M(),optional:M()}),P({id:k().min(1),type:B(`text`),prompt:k(),multiline:M(),secret:B(!1),optional:M(),placeholder:k().optional(),prefill:k().optional()})]),Oc=P({interactionId:k().min(1),turnId:k().min(1),title:k().optional(),questions:N(Dc).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});F({threadId:k().min(1)}),P({questions:N(Oc)}),F({threadId:k().min(1),turnId:k().min(1),interactionId:k().min(1),answers:R(k(),N(k())),cancelled:M().default(!1)}),P({accepted:B(!0)});let kc=/* @__PURE__ */ new Set([`codexhostTurnChanges`,`codexhostToolOutput`]),Ac=P({path:k(),oldText:k().nullable(),newText:k()});P({sessionId:k().min(1),turn:j().int().nonnegative(),path:k().min(1).optional()}),P({diffs:N(Ac)}),F({}),F({}),P({reference:P({sessionId:k().min(1),epoch:k().min(1),turn:j().int().nonnegative(),seq:j().int().nonnegative(),callId:k().min(1),part:j().int().nonnegative(),version:k().min(1)}),length:j().int().nonnegative(),bytes:j().int().nonnegative()}),F({title:k().trim().min(1).max(200),type:z([`info`,`warning`,`danger`]),body:k().trim().min(1).max(16384)}),F({}),F({url:k().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 jc=z([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),Mc=z([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);F({threadId:k(),title:k(),harnessId:k(),state:jc,reason:Mc,inactiveMs:j().nonnegative()}),F({threadId:W,turnId:ms});let Nc=P({amount:j().finite().nonnegative(),currency:k().trim().min(1).max(8),label:k().trim().min(1).max(128).optional()}).strict(),Pc=P({email:k().trim().min(1).max(320).optional(),label:k().trim().min(1).max(256).optional(),plan:k().trim().min(1).max(128).optional(),credits:Ds.optional(),balance:Nc.optional()}).strict();function Fc(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 Ic=Fc(Pc),Lc={harnessId:U,harnessName:k().trim().min(1).max(128)},Rc=P(Lc).strict();P({}).strict(),P({sources:N(Rc).max(128)}).strict(),P({harnessId:U,refresh:M().optional()}).strict(),P({...Lc,account:Ic.nullable(),accounts:N(Ic).max(8).optional()}).strict(),P({refresh:M().optional()}).strict(),P({accounts:N(Fc(Pc.extend(Lc))).max(128)}).strict();let zc=k().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).pipe(U),Bc=zc.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Vc=k().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`),Hc=qa().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),Uc=P({en:k().max(4096),"zh-CN":k().max(4096).optional()}).strict(),Wc=P({commands:N(P({terminal:k().max(256),command:k().max(4096)}).strict()).max(8),before:Uc.optional(),after:Uc.optional(),downloads:N(P({label:k().max(128),url:Hc}).strict()).max(8).optional()}).strict(),Gc={id:zc,name:k().trim().min(1).max(128),version:k().min(1).max(128),kind:B(`usage`).optional(),iconStyle:P({vector:P({viewBox:k().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:N(P({d:k().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:z([`evenodd`,`nonzero`]).optional(),fill:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:k().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:j().min(0).max(50).optional(),paddingRatio:j().min(0).max(.25).optional()}).strict().optional(),installation:Wc.optional(),notice:Uc.optional(),launchCommand:B(!0).optional(),links:P({website:Hc.optional(),documentation:Hc.optional(),installation:Hc.optional()}).strict().optional()};P({manifestVersion:B(1),...Gc,adapterApiVersion:j().int().positive(),entry:Vc,icon:Vc.optional()}).strict();let Kc=k().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),qc=P({...Gc,icon:Kc.optional()}).strict();P({}).strict(),P({plugins:N(qc.extend({id:Bc})).max(128)}).strict(),P({version:B(1),enabled:N(zc).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]}),P({harnessId:Bc,model:J.optional(),thinkingOptionId:Y.optional(),permissionModeId:G.optional(),prewarm:B(!0).optional()}).strict();let Jc=k().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);P({harnessId:Bc}).strict().extend({path:Jc.nullable()}),P({path:Jc.nullable(),restartRequired:M()}).strict(),P({harnessId:U,action:z([`check`,`update`,`install`])}).strict();let Yc=P({currentVersion:k().min(1).max(128),latestVersion:k().min(1).max(128),updateAvailable:M(),canUpdate:M(),versionKind:z([`cli`,`application`]).optional(),manualUpdateUrl:qa().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:k().max(2048).optional(),messageCode:k().min(1).max(128).optional(),notice:fs.optional(),latestVersionKind:z([`unknown`,`tracking-branch`]).optional()}).strict();P({taskId:k().uuid()}).strict(),L(`status`,[P({taskId:k().uuid(),status:B(`running`)}).strict(),P({taskId:k().uuid(),status:B(`succeeded`),result:Yc}).strict(),P({taskId:k().uuid(),status:B(`failed`),error:P({code:j().int(),message:k().min(1).max(2048)}).strict()}).strict()]);let Xc=k().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Zc=k().trim().min(1),Qc=z([`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`]),$c=P({accountId:Xc,label:Zc.max(256),email:k().email().max(320).optional(),planType:Qc.optional()}).strict(),el=z([`ready`,`unavailable`]);P({version:B(2),currentAccountId:Xc.nullable(),phase:el,revision:j().int().nonnegative(),instanceId:Zc.max(1024).optional(),accounts:N($c).max(1)}).strict(),P({accountId:Xc,refresh:M().optional()}).strict(),P({accountId:Xc,usage:xs.nullable(),accountCredits:Ds.optional(),freshness:z([`live`,`cached`]),observedAt:k().datetime().nullable()}).strict();let tl=1e3,nl=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),rl=nl.max(1024),il=P({nativeSessionId:rl,title:nl.max(4096).nullable(),updatedAt:j().int().nonnegative().max(864e13),cwd:nl.max(16384),running:M().nullable()}).strict();P({}).strict(),P({harnesses:N(P({harnessId:Bc,name:nl.max(128)}).strict()).max(128)}).strict(),P({harnessId:Bc,query:k().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:j().int().nonnegative().safe().optional(),limit:j().int().min(1).max(tl).optional()}).strict(),P({candidates:N(il).max(tl),total:j().int().nonnegative().safe()}).strict(),P({harnessId:Bc,nativeSessionId:rl}).strict(),P({threadId:nl.max(1024).pipe(W)}).strict();let al=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),ol=rl,sl=il;P({}).strict(),P({candidates:N(sl).max(1e3)}).strict(),P({nativeSessionId:ol}).strict(),P({threadId:al.max(1024).pipe(W)}).strict(),P({threadId:W,lastTurnId:ms}).strict(),P({threadId:W}).strict();let cl=k().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();P({commands:N(P({id:cl,invocation:k().min(1).max(128),label:k().trim().min(1).max(128),description:k().trim().min(1).max(512).optional(),localizations:ds.optional(),argumentMode:z([`none`,`text`]),kind:z([`command`,`skill`]).optional()}).strict()),warnings:N(k().min(1)).optional(),source:z([`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)}),P({harnessId:U,cwd:k().min(1).optional()}).strict(),P({threadId:W}).strict(),P({threadId:W,commandId:cl,turnId:ms.optional(),arguments:ss.optional()}).strict(),P({accepted:B(!0),turnId:ms.optional()}).strict();let ll=B(`2.0`).optional(),$=yo().optional(),ul=k().min(1),dl=I([k(),j().int()]),fl=P({code:j().int(),message:k(),data:H.optional()}).catchall(H).superRefine(V([`data`]));I([P({jsonrpc:ll,id:dl,method:ul,params:H.optional(),result:$,error:$}).catchall(H).superRefine(V([`jsonrpc`,`params`,`result`,`error`])),P({jsonrpc:ll,id:$,method:ul,params:H.optional(),result:$,error:$}).catchall(H).superRefine(V([`jsonrpc`,`id`,`params`,`result`,`error`])),P({jsonrpc:ll,id:dl,method:$,params:$,result:H,error:$}).catchall(H).superRefine(V([`jsonrpc`,`method`,`params`,`error`])),P({jsonrpc:ll,id:dl,method:$,params:$,result:$,error:fl}).catchall(H).superRefine(V([`jsonrpc`,`method`,`params`,`result`]))]);let pl=k().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});F({harnessId:U,nativeSessionId:pl,locator:H.optional(),formatVersion:B(1)}).superRefine(V([`locator`])),F({harnessId:U,nativeSessionId:pl,nativeTurnKey:pl,formatVersion:B(1)}),F({harnessId:U,nativeSessionId:pl,checkpointId:pl,locator:H.optional(),formatVersion:B(1)}).superRefine(V([`locator`]));let ml=k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),hl=z([`npm`,`windows-installer`,`macos-dmg`]),gl=F({version:ml,installation:hl,phase:z([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:j().int().nonnegative(),downloadedBytes:j().int().nonnegative().optional(),totalBytes:j().int().positive().optional(),error:k().min(1).max(500).nullable(),serviceStopOutput:k().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`})});F({});let _l=k().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`);F({currentVersion:ml,installation:hl.nullable(),latestVersion:ml.nullable(),updateAvailable:M(),installationAvailable:M(),releaseNotes:k().min(1).max(2e4).nullable(),releaseNotesUrl:_l.nullable(),status:gl.nullable(),error:k().min(1).max(500).nullable()}),F({status:gl}),F({status:gl.nullable()});let vl=z([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);P({runningVersion:k().nullable(),installedVersion:k().nullable(),restartRequired:M(),remote:M(),updateSupported:M(),update:P({phase:vl,targetVersion:k().nullable(),error:k().nullable()})});let yl=P({version:k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();P({hostname:k().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),action:z([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:M().optional(),version:k().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),P({state:z([`installed`,`not-installed`])}).strict();let bl=k().min(1).max(1024),xl=P({hostId:bl,displayName:k().min(1).max(1024),source:z([`codex-managed`,`discovered`]),sshAlias:k().max(1024).nullable(),sshHost:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),autoConnect:M(),connectionAnalyticsId:k().max(1024).optional()}),Sl=F({displayName:k().min(1).max(1024),hostname:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable()});L(`action`,[F({action:B(`list`)}),F({action:B(`read-thread`),hostId:bl.refine(e=>e!==`local`),input:nc}),F({action:B(`save`),draft:Sl,previous:xl.nullable()}),F({action:B(`remove`),previous:xl}),F({action:B(`connect`),hostId:bl,enabled:M()}),F({action:B(`state`),hostId:bl}),F({action:B(`runtime`),hostId:bl}),F({action:B(`update`),hostId:bl.refine(e=>e!==`local`),version:yl.shape.version})]),I([F({result:H}),F({error:F({code:j().int(),message:k()})})]);let Cl=k().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),wl=I([k(),P({en:k()}).catchall(k())]),Tl=P({title:wl.optional(),description:wl.optional(),icon:k().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:k().optional()});P({extensions:N(P({id:Cl,name:k().min(1).max(214),version:k().min(1).max(128),format:B(`dsh`),supportedTargets:Do([B(`web`)]),enabledTargets:N(B(`web`)).max(1),source:k().min(1).max(4096),projectUrl:k().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:k(),meta:Tl.optional(),loadError:k().optional()})),loadedIds:N(Cl),safeMode:M(),storeError:k().optional()});let El=k().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}/`);P({spec:k().trim().min(1).max(4096),registry:El.optional()}).strict(),P({id:Cl,enabled:M()}).strict(),P({id:Cl}).strict(),B(1);function Dl(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
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
125
|
/* v8 ignore next -- dense-array guard: following is bounded by baseline.length. */
|
|
@@ -135,6 +135,6 @@ if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0
|
|
|
135
135
|
/* v8 ignore next -- the loop condition guarantees one pending task. */
|
|
136
136
|
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
137
|
/* 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 Vl(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 Hl=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]`))}},Ul=class{rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;anyNotifier=new Hl(()=>{});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(){for(let e of this.rows.keys())this.rows.delete(e),this.changed(e)}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 Hl(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},Wl=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 Gl(){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 Kl(e){return{kind:`leaf`,entries:e,length:e.length}}function ql(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Jl(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 Yl(e,t,n,r){let i;return{get entries(){return i??=Jl(e),i},hasMore:t,revision:n,change:r}}var Xl=class{listeners=/* @__PURE__ */ new Set;window=Kl([]);snapshot=Yl(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=Kl(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=ql(Kl(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=ql(this.window,Kl(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Jl(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=Kl(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Yl(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Zl(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Ql(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function $l(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 eu(e){let t=zl(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function tu(e){let t=[];for(let n of e){let e=nu(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 nu(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`:{au(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=iu(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return ru(t,e.length,t.type),t}case`tool-call-chunks`:{au(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=iu(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 ru(t,e.length,t.type),t}case`chunk`:{au(t,[`type`,`time`,`chunk`],`chunk`);let e=Ql(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=eu(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Bl({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function ru(e,t,n){if(Ql(e.time0),$l(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 iu(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function au(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 ou=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;replace(e,t){this.pending.clear(),this.transientInGap=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 tu(n.stream).entries())if(this.transientInGap+=1,r.push({type:`transient`,event:{type:`assistant/live-chunk`,seq:this.durableCursor+1-1/(this.transientInGap+1),time:t.time,data:{attemptId:n.attemptId,turn:n.turn,step:n.step,chunk: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=su(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,this.transientInGap+=1,{type:`transient`,entry:{type:`transient`,event:{type:`assistant/live-chunk`,seq:this.durableCursor+1-1/(this.transientInGap+1),time:e.time,data:{attemptId:e.attemptId,turn:t.turn,step:t.step,chunk: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}))}}}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 su(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function cu(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let lu={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},uu={...lu,turnWindow:{...lu.turnWindow,minMessages:200}};var du=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 ou;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;lastAgentError=null;pendingSubmissions=[];submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Xl;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Wl(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Ul,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 Hl(()=>{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=Gl(),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,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}async prompt(e,t,n,r){this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let i;if(this.address===void 0){let a=Zl();i=await this.remote.session.prompt({requestId:r??Gl(),sessionId:this.sessionId,mode:t,content:e,clientTimeZone:a},n)}else if(e.some(e=>e.type===`file`))i={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:Gl(),parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Zl()},n);i=a.ok?{ok:!0,value:{accepted:!0}}:a}return i.ok?(this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this),i):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:i.error},this.notifier.markDirty(),i)}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,...lu})}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,...uu}),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;this.openGeneration++;let e=this.events;this.cachedJournal=e?.capture()??this.cachedJournal,this.events=void 0,await e?.dispose(),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(kc),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(lu),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:cu(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,kc),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)}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(this.submissionSettlements.size!==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)}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);else e.type===`user/message`&&this.observeSubmissionMessage(e.data,!0)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;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:pu(a.content)})}}observeSubmissionMessage(e,t){let n=e.source;if(n.kind!==`user`||!(`rpcId`in n))return;let r=this.submissionSettlements.get(n.rpcId);r===void 0||r.retiring||(t?(r.admitted=pu(e.content),this.retireAdmittedSubmission(n.rpcId)):r.placement===`queued`&&this.scheduleObservedRetirement(n.rpcId,pu(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)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)}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,fu(()=>{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);
|
|
138
|
+
t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function Vl(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 Hl=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]`))}},Ul=class{rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;anyNotifier=new Hl(()=>{});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(){for(let e of this.rows.keys())this.rows.delete(e),this.changed(e)}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 Hl(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},Wl=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 Gl(){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 Kl(e){return{kind:`leaf`,entries:e,length:e.length}}function ql(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Jl(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 Yl(e,t,n,r){let i;return{get entries(){return i??=Jl(e),i},hasMore:t,revision:n,change:r}}var Xl=class{listeners=/* @__PURE__ */ new Set;window=Kl([]);snapshot=Yl(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=Kl(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=ql(Kl(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=ql(this.window,Kl(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Jl(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=Kl(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Yl(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Zl(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Ql(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function $l(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 eu(e){let t=zl(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function tu(e){let t=[];for(let n of e){let e=nu(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 nu(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`:{au(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=iu(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return ru(t,e.length,t.type),t}case`tool-call-chunks`:{au(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=iu(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 ru(t,e.length,t.type),t}case`chunk`:{au(t,[`type`,`time`,`chunk`],`chunk`);let e=Ql(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=eu(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Bl({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function ru(e,t,n){if(Ql(e.time0),$l(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 iu(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function au(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 ou=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;replace(e,t){this.pending.clear(),this.transientInGap=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 tu(n.stream).entries())if(this.transientInGap+=1,r.push({type:`transient`,event:{type:`assistant/live-chunk`,seq:this.durableCursor+1-1/(this.transientInGap+1),time:t.time,data:{attemptId:n.attemptId,turn:n.turn,step:n.step,chunk: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=su(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,this.transientInGap+=1,{type:`transient`,entry:{type:`transient`,event:{type:`assistant/live-chunk`,seq:this.durableCursor+1-1/(this.transientInGap+1),time:e.time,data:{attemptId:e.attemptId,turn:t.turn,step:t.step,chunk: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}))}}}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 su(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function cu(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let lu={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},uu={...lu,turnWindow:{...lu.turnWindow,minMessages:200}};var du=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 ou;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;lastAgentError=null;pendingSubmissions=[];submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Xl;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Wl(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Ul,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 Hl(()=>{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=Gl(),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,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}async prompt(e,t,n,r){this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let i;if(this.address===void 0){let a=Zl();i=await this.remote.session.prompt({requestId:r??Gl(),sessionId:this.sessionId,mode:t,content:e,clientTimeZone:a},n)}else if(e.some(e=>e.type===`file`))i={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:Gl(),parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Zl()},n);i=a.ok?{ok:!0,value:{accepted:!0}}:a}return i.ok?(this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this),i):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:i.error},this.notifier.markDirty(),i)}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,...lu})}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,...uu}),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;this.openGeneration++;let e=this.events;this.cachedJournal=e?.capture()??this.cachedJournal,this.events=void 0,await e?.dispose(),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(kc),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(lu),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:cu(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,kc),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)}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(this.submissionSettlements.size!==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);else e.type===`user/message`&&this.observeSubmissionMessage(e.data,!0)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;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:pu(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=pu(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,pu(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)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,fu(()=>{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
139
|
/* 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 fu(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function pu(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 mu=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 hu(e){return e===-1?-1:p(e)}var gu=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new mu;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];listState=`idle`;listPhase=`pending`;listError=null;listInflight=null;includeArchived=!1;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];notifier=new Hl(()=>{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(kc)}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 du(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 Ul;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:hu(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.listMutations=null,this.listInflight=null,this.refreshList())}refreshList(){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let e=this.includeArchived;this.listState=`loading`,this.listError=null;let t=this.summaries,n=[];return this.listMutations=n,this.notifier.markDirty(),this.listInflight=(async()=>{try{let r=await this.remote.session.list({includeArchived:e});if(this.listMutations!==n)return;if(r.ok){let i=new Set(r.value.archivedSessionIds),a=new Set(r.value.items.map(e=>e.sessionId)),o=[...r.value.items,...e?[]:t.filter(e=>i.has(e.sessionId)&&!a.has(e.sessionId))],s=this.listPhase===`pending`?o:Dl(t,o,e=>e.sessionId),c=/* @__PURE__ */ new Set;for(let e of n)e.kind===`remove`&&c.add(e.sessionId);for(let e of s)e.running&&!c.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let l=n.reduce(_u,s);this.summaries=l;let u=this.retainedIds(l);for(let e of this.engagedSessions)this.pruneEngagement(e,u);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 r.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}else this.listState=`error`,this.listError=r.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==n)return;this.listState=`error`,this.listError=e}finally{this.listMutations===n&&(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],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=vu(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:vu(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=_u(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=hu(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,kc)}this.notifier.markDirty()}handleSessionAdded(e){this.mergeSummary(e),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let t=this.sessions.get(e.sessionId);t?.handleRestored(),t?.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=hu(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:Ml(t.kind,`session list projection block kind`)}}handleSessionRemoved(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();this.listMutations=null,this.listInflight=null,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=Vl(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,state:this.listState,phase:this.listPhase,error:this.listError,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([e,t])=>[e,{values:t.values(),state:`idle`,error:null,...this.projectionLoads.get(e)}]))}}};function _u(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 vu(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var yu=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},bu=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 xu(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 Su(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 Cu(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let wu=Object.freeze({referenceCount:0,retainedBy:Cu({})});async function Tu(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 Eu=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]);Tu(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()}},Du=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 gu(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,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}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}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 yu(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 bu(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,Su(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:Cu({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new Eu(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?wu:Object.freeze({referenceCount:r,retainedBy:Cu(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??wu}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:wu,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}=this.manager.getListSnapshot(),i=[],a={};for(let e of t)i.push(e.sessionId),a[e.sessionId]={id:e.sessionId,displayTitle:xu(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=a[t],i=r?.projectionValues??this.manager.projectionValues(t),o=i?.title,s=typeof o==`string`&&o!==``?o:void 0,c=s??n.label??t;r===void 0?a[t]={id:t,displayTitle:c,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},...s===void 0?{}:{title:s}}:(r.displayTitle!==c||r.projectionValues!==i)&&(a[t]={...r,displayTitle:c,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(a[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],o=n.session.getSnapshot(),s=this.manager.projectionValues(t),c=s?.title,l=typeof c==`string`&&c!==``?c:i?.title;a[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:o.running,retainedBy:n.retention.retainedBy,blank:o.blank,parentId:r.parentSessionId,origin:`subagent`,...s===void 0?{}:{projectionValues:s},...l===void 0?{}:{title:l,displayTitle:l}}}this.list.set({ids:i,byId:a,phase:n,projectionsBySession:r})}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 Ou=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function ku(e){let t=e.remote,n=e.get(`connection`),r=new Du(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=Xl,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=yu,n.SessionEventStream=pe,n.SessionForkError=bu,n.apply=ku,n.createScope=_e,n.createSessionControlStream=fe,n.inject=Ou,n.scopeOf=ve,t.exports}});
|
|
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 fu(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function pu(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 mu=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 hu(e){return e===-1?-1:p(e)}var gu=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new mu;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 Hl(()=>{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(kc)}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 du(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 Ul;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:hu(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:Dl(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(_u,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=vu(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:vu(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=_u(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=hu(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,kc)}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=hu(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:Ml(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();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=Vl(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 _u(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 vu(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var yu=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},bu=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 xu(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 Su(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 Cu(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let wu=Object.freeze({referenceCount:0,retainedBy:Cu({})});async function Tu(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 Eu=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]);Tu(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()}},Du=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 gu(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}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 yu(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 bu(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,Su(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:Cu({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new Eu(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?wu:Object.freeze({referenceCount:r,retainedBy:Cu(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??wu}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:wu,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:xu(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 Ou=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function ku(e){let t=e.remote,n=e.get(`connection`),r=new Du(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=Xl,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=yu,n.SessionEventStream=pe,n.SessionForkError=bu,n.apply=ku,n.createScope=_e,n.createSessionControlStream=fe,n.inject=Ou,n.scopeOf=ve,t.exports}});
|