@codexhost/cli-win32-x64 0.29.2 → 0.31.0
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 +94 -20
- package/app/console-web.js +123 -31
- package/app/desktop-controller.mjs +113 -37
- package/app/host-runtime.mjs +3963 -2280
- package/app/plugins/antigravity/plugin.mjs +94 -20
- package/app/plugins/claude-code/plugin.mjs +105 -28
- package/app/plugins/codebuddy/plugin.mjs +767 -202
- package/app/plugins/codex-usage/plugin.mjs +112 -38
- package/app/plugins/copilot/plugin.mjs +94 -20
- package/app/plugins/cursor-cli/plugin.mjs +94 -20
- package/app/plugins/deepseek-harness/plugin.mjs +94 -20
- package/app/plugins/devin/plugin.mjs +94 -20
- package/app/plugins/grok/plugin.mjs +94 -20
- package/app/plugins/hermes/plugin.mjs +94 -20
- package/app/plugins/kimi-code/plugin.mjs +94 -20
- package/app/plugins/kiro-cli/plugin.mjs +94 -20
- package/app/plugins/omp/plugin.mjs +94 -20
- package/app/plugins/opencode/plugin.mjs +94 -20
- package/app/plugins/pi/plugin.mjs +94 -20
- package/app/plugins/qoder/plugin.mjs +94 -20
- package/app/plugins/qoder-cn/plugin.mjs +94 -20
- package/app/plugins/qwen-code/plugin.mjs +94 -20
- package/app/plugins/workbuddy/plugin.mjs +798 -202
- package/app/plugins/zcode/plugin.mjs +94 -20
- package/app/renderer-extension.js +702 -440
- package/app/web/assets/abnfDiagram-XWFEHMT6-Bqy7uOSy.js +1 -0
- package/app/web/assets/architectureDiagram-CSQXQB3N-6aaP1YoM.js +36 -0
- package/app/web/assets/blockDiagram-BEDRHYPZ-B4QSFXe0.js +140 -0
- package/app/web/assets/bpmnIcons-APHXDYXF-ByGoYv9M.js +1 -0
- package/app/web/assets/c4Diagram-M2UUVUY5-BYE-C8Gq.js +38 -0
- package/app/web/assets/chunk-2Q5K7J3B-CiEM-GTd.js +1 -0
- package/app/web/assets/chunk-3GCGMST5-hzY9BiB1.js +1 -0
- package/app/web/assets/chunk-5VM5RSS4-DYXznY0H.js +15 -0
- package/app/web/assets/chunk-7U7NFRK5-Bzw5MDPr.js +88 -0
- package/app/web/assets/chunk-CNRTWJTD-DMbxMfi3.js +1 -0
- package/app/web/assets/chunk-D5HYT7QG-By0ZVBtD.js +1 -0
- package/app/web/assets/chunk-EBZ3SEQC-Yyu_sMV7.js +2 -0
- package/app/web/assets/chunk-JWPE2WC7-DDzqxIPT.js +1 -0
- package/app/web/assets/chunk-KTR4FSNJ-GlKqhtpl.js +1 -0
- package/app/web/assets/chunk-XXDRQBXY-DNc-CvYu.js +1 -0
- package/app/web/assets/classDiagram-v2-KXABOMEV-4_PFS2N_.js +217 -0
- package/app/web/assets/cose-bilkent-JH36ORCC-BE3foHUY.js +1 -0
- package/app/web/assets/cynefin-EF2NZ3EQ-D2PqrYZ3.js +141 -0
- package/app/web/assets/cynefinDiagram-NJNITYFG-DOObpTbq.js +62 -0
- package/app/web/assets/cytoscape.esm-Cm0uQArZ.js +332 -0
- package/app/web/assets/d3-scale-4DPf7zan.js +1 -0
- package/app/web/assets/dagre-KIHZ2IZ3-Znm2jin9.js +4 -0
- package/app/web/assets/diagram-7YQZDPLS-ByZMD-uA.js +41 -0
- package/app/web/assets/diagram-QBROCOUO-BiRShpnN.js +200 -0
- package/app/web/assets/diagram-RJJCUUZO-D9wLVoK2.js +30 -0
- package/app/web/assets/diagram-WERXNKYE-BSbIh-yC.js +24 -0
- package/app/web/assets/diagram-YHHI257C-DMWrHMc8.js +3 -0
- package/app/web/assets/diagram-YR4HJLHV-C4sBAFb1.js +24 -0
- package/app/web/assets/ebnfDiagram-N527522P-BZLloaoQ.js +1 -0
- package/app/web/assets/elk-O5DQBFGD-Da3e5tn5.js +27 -0
- package/app/web/assets/erDiagram-K3K3BIDK-B2lKAIZF.js +99 -0
- package/app/web/assets/flowDiagram-Z6JWZHQI-q2EY_kmB.js +213 -0
- package/app/web/assets/ganttDiagram-3PRQTZWP-BGrNZ20b.js +292 -0
- package/app/web/assets/gitGraphDiagram-VXDFKS5L-DIZNXREy.js +106 -0
- package/app/web/assets/graph-D8UmR1vK.js +1 -0
- package/app/web/assets/grid-E2QIVN74-0cUkPG69.js +1 -0
- package/app/web/assets/{index-aSHN2MIG.css → index-BbmB5VLj.css} +1 -1
- package/app/web/assets/{index-0TnaYwHS.js → index-PN7K-15_.js} +78 -78
- package/app/web/assets/infoDiagram-EZ3ZOAHP-BHhUTQCn.js +2 -0
- package/app/web/assets/ishikawaDiagram-S3EKX5GW-DPOxtl4c.js +70 -0
- package/app/web/assets/journeyDiagram-POQNLL5X-D8RyXckG.js +139 -0
- package/app/web/assets/kanban-definition-BH5XI6FM-COJv3Hyh.js +89 -0
- package/app/web/assets/langs/{graphql-ChAeyPkT.js → graphql-D6Z3qcRW.js} +1 -1
- package/app/web/assets/langs/{http-BvreBIbD.js → http-XiU9G9In.js} +1 -1
- package/app/web/assets/langs/{php-D8omCIuJ.js → php-DL3xwS-7.js} +1 -1
- package/app/web/assets/langs/{rst-Do7RLLCS.js → rst-DudRVJ9g.js} +1 -1
- package/app/web/assets/langs/{ruby-rH_O_vse.js → ruby-_FqsfqJi.js} +1 -1
- package/app/web/assets/langs/{svelte-xZy73wAj.js → svelte-ClsVJoBT.js} +1 -1
- package/app/web/assets/langs/{vue-C4DW8agZ.js → vue-BiKMXCyK.js} +1 -1
- package/app/web/assets/mermaid.core-DYdcDKIt.js +314 -0
- package/app/web/assets/mindmap-definition-WVAN44T4-DnYIM4ja.js +98 -0
- package/app/web/assets/pegDiagram-D4NLKWP3-Ds3GAEJ6.js +1 -0
- package/app/web/assets/pieDiagram-36ENHN4W-BhLUJGEB.js +39 -0
- package/app/web/assets/quadrantDiagram-ZQUDMS73-DwtX-IxK.js +7 -0
- package/app/web/assets/railroadDiagram-JIZHGYPL-D2vmTTnJ.js +1 -0
- package/app/web/assets/render-VIF2ZAQL-DGU1ql-Z.js +2 -0
- package/app/web/assets/requirementDiagram-AXW2TVFA-u3j1sKkI.js +84 -0
- package/app/web/assets/sankeyDiagram-FBCJTAIF-k-An9VHW.js +40 -0
- package/app/web/assets/sequenceDiagram-3LA2ROMG-DUjbYb4R.js +169 -0
- package/app/web/assets/sizeCapture-2Q2CQKSF-DATTL7FZ.js +1 -0
- package/app/web/assets/stateDiagram-v2-ATKHQDJO-cCJX5M2u.js +291 -0
- package/app/web/assets/swimlanes-YQL5WMAO-B7grWEWt.js +1 -0
- package/app/web/assets/swimlanesDiagram-UCCPES4V-B8Jem9gq.js +8 -0
- package/app/web/assets/timeline-definition-7Z437IG3-BhsLa6l1.js +120 -0
- package/app/web/assets/usecaseDiagram-RDK6N6HP-CkPQYmQw.js +370 -0
- package/app/web/assets/vendor-BKfNgqAm.js +666 -0
- package/app/web/assets/vennDiagram-SHRQU5PJ-CufZSwvw.js +34 -0
- package/app/web/assets/wardleyDiagram-F3OXNVQS-CSkfpFOA.js +78 -0
- package/app/web/assets/xychartDiagram-GDYJKCDI-BhZf9scK.js +7 -0
- package/app/web/codexhost-settings.js +57 -57
- package/app/web/index.html +3 -3
- package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +65 -65
- package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
- package/app/web/plugins/deepseek-ai__dsh-api-workspace-controller/client.js +3 -3
- package/app/web/plugins/deepseek-ai__dsh-client-locale/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +75 -75
- package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +12 -12
- package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +16 -16
- package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +3 -3
- package/app/web/plugins/deepseek-ai__dsh-client-ui-permission-presets/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-plan/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
- package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
- package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +70 -72
- package/app/web-modules/licenses/DSH-THIRD_PARTY_NOTICES.md +1 -1
- package/app/web-modules/server.mjs +724 -259
- package/bin/codexhost.exe +0 -0
- package/libexec/codexhost-node-repl.exe +0 -0
- package/libexec/codexhost-screenshot.exe +0 -0
- package/libexec/codexhost-shell.exe +0 -0
- package/libexec/codexhost-shim.exe +0 -0
- package/libexec/codexhost-updater.exe +0 -0
- package/package.json +1 -1
- package/app/web/assets/vendor-C9g2bw8s.js +0 -410
|
@@ -110,20 +110,20 @@ function go(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}//
|
|
|
110
110
|
function _o(e,t){let n=/* @__PURE__ */ vo(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(gt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(gt(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
|
|
111
111
|
function vo(e,t){let n=new x({check:`custom`,...g(t)});return n._zod.check=e,n}function yo(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ae(e,t,n[t]);return e}function bo(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??fa,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function xo(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function w(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),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;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,w(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&yo(o.schema,c),t.io===`input`&&T(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 So(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Co(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;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}/${So(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+So(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>
|
|
112
112
|
|
|
113
|
-
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)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function wo(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;wo(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}let To=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Eo=[`oneOf`,`anyOf`];function Do(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Oo(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!To.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??Do(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ae(n,r,e.length===1?e[0]:Oo(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=Do(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function ko(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of To)if(t in e)return;let n=t.filter(e=>Eo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Oo(t);else{let e=n[0],i=Eo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Oo([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,yo(e,r))}function Ao(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)):yo(i,s),yo(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??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())wo(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])ko(e)}}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)}yo(i,n.defId?n.schema: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??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ae(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),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:Mo(t,`input`,e.processors),output:Mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function T(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 T(r.element,n);if(r.type===`set`)return T(r.valueType,n);if(r.type===`lazy`)return T(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`||r.type===`catch`)return T(r.innerType,n);if(r.type===`intersection`)return T(r.left,n)||T(r.right,n);if(r.type===`record`||r.type===`map`)return T(r.keyType,n)||T(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:T(r.in,n)||T(r.out,n);if(r.type===`object`){for(let e in r.shape)if(T(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(T(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(T(e,n))return!0;return!!(r.rest&&T(r.rest,n))}return!1}let jo=(e,t={})=>n=>{let r=bo({...n,processors:t});return w(e,r),Co(r,e),Ao(r,e)},Mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=bo({...i??{},target:a,io:t,processors:n});return w(e,o),Co(o,e),Ao(o,e)},No=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Po=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Fo=(e,t)=>{No(e,`minimum`,t),Po(e,`maximum`,t)},Io=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Lo=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Ro=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},zo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Bo=(e,t)=>No(e,`minimum`,t.minimum),Vo=(e,t)=>Po(e,`maximum`,t.maximum),Ho=e=>(t,n)=>{zo(t,n.format);let[r,i]=e[n.format];No(t,`minimum`,r),Po(t,`maximum`,i)},Uo={greater_than:(e,t)=>No(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>Po(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Io(e,t.value),number_format:Ho(Ye),bigint_format:Ho(Xe),min_length:Bo,max_length:Vo,length_equals:(e,t)=>Fo(e,t.length),min_size:Bo,max_size:Vo,size_equals:(e,t)=>Fo(e,t.size),string_format:(e,t)=>{zo(e,t.format),t.pattern&&Lo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Ro(e,t.mime)};function E(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Uo[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&No(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&No(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&Po(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&Po(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Io(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Ro(t,i.mime);for(let e of i.patterns??[])Lo(t,e);return t}let Wo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Go=/* @__PURE__ */ new Map([[Wr,On],[Kr,kn]]),Ko=e=>Go.get(e)??e,qo=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=E(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Wo[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Ko);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}))])}},Jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=E(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):xo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Yo=(e,t,n,r)=>{n.type=`boolean`},Xo=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Zo=(e,t,n,r)=>{n.not={}},Qo=(e,t,n,r)=>{let i=e._zod.def,a=be(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},$o=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(xo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(xo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);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}},es=(e,t,n,r)=>{xo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},ts=(e,t,n,r)=>{xo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ns=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=E(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=w(a.element,t,{...r,path:[...r.path,`items`]})};function rs(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?rs(t.out):t.type===`catch`?rs(t.innerType):e._zod.optin}let is=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&xo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ae(i.properties,e,w(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?rs(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=w(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},as=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>w(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},os=(e,t,n,r)=>{let i=e._zod.def,a=w(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=w(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},ss=(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)=>w(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?w(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?rs(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=E(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function cs(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=cs(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>cs(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Bn:zn).source)),p}let ls=/* @__PURE__ */ new WeakMap;function us(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of ls.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=cs(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}let ds=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=E(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=w(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ae(i.patternProperties,Ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=w(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=ls.get(t);n||(n=[],ls.set(t,n),t.deferred.push(()=>us(t))),n.push(e)}i.additionalProperties=w(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&rs(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},fs=(e,t,n,r)=>{let i=e._zod.def,a=w(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`}]},ps=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ms=Symbol();function hs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(xo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),ms):JSON.parse(o)}let gs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=hs(i.defaultValue,e,t,n,r);o!==ms&&(n.default=o)},_s=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=hs(i.defaultValue,e,t,n,r);o!==ms&&(n._prefault=o)},vs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{xo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},ys=(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;w(o,t,r);let s=t.seen.get(e);s.ref=o},bs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},xs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ss=(e,t,n,r)=>{let i=e._zod.innerType;w(i,t,r);let a=t.seen.get(e);a.ref=i},Cs=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function ws(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}let D=/*@__PURE__*/ y(`ZodError`,(e,t)=>{Ht.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Cs.has(n)||(Cs.add(n),ws(n,`format`,e=>t=>Gt(e,t)),ws(n,`flatten`,e=>t=>Wt(e,t)),ws(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),ws(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Se,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Ts=/* @__PURE__ */ qt(D),Es=/* @__PURE__ */ Jt(D),Ds=/* @__PURE__ */ Yt(D),Os=/* @__PURE__ */ Zt(D),ks=/* @__PURE__ */ rn(D),As=/* @__PURE__ */ an(D),js=/* @__PURE__ */ on(D),Ms=/* @__PURE__ */ sn(D),Ns=/* @__PURE__ */ cn(D),Ps=/* @__PURE__ */ ln(D),Fs=/* @__PURE__ */ un(D),Is=/* @__PURE__ */ dn(D);function Ls(){b.localeError||Ft(ca())}function Rs(){b.memoizer||Ft({memoizer:aa()})}let O=/*@__PURE__*/ y(`ZodType`,(e,t)=>(Ls(),S.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(h(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 Ke(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(nl(e,t))},superRefine(e,t){return this.check(rl(e,t))},overwrite(e){return this.check(/* @__PURE__ */ so(e))},optional(){return Fc(this)},exactOptional(){return Lc(this)},nullable(){return zc(this)},nullish(){return Fc(zc(this))},nonoptional(e){return Gc(this,e)},array(){return P(this)},or(e){return L([this,e])},and(e){return Ec(this,e)},transform(e){return Yc(this,Nc(e))},default(e){return Vc(this,e)},prefault(e){return Uc(this,e)},catch(e){return qc(this,e)},pipe(e){return Yc(this,e)},readonly(){return Zc(this)},describe(e){let t=this.clone();return fa.add(t,{description:e}),t},meta(...e){if(e.length===0)return fa.get(this);let t=this.clone();return fa.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return yt(this,`~standard`,{...fr(this),jsonSchema:{input:Mo(this,`input`),output:Mo(this,`output`)}})},set"~standard"(e){vt(this,`~standard`,e)},parse:function e(t,n){return Ts(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Es(this,t,n,{callee:e})},safeParse(e,t){return Ds(this,e,t)},async safeParseAsync(e,t){return Os(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){vt(this,`spa`,e)},validate(e,t){return en(this,e,t)},validateAsync(e,t){return nn(this,e,t)},encode:function e(t,n){return ks(this,t,n,{callee:e})},decode:function e(t,n){return As(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await js(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Ms(this,t,n,{callee:e})},safeEncode(e,t){return Ns(this,e,t)},safeDecode(e,t){return Ps(this,e,t)},async safeEncodeAsync(e,t){return Fs(this,e,t)},async safeDecodeAsync(e,t){return Is(this,e,t)},toJSONSchema(e){return jo(this,{})(e)},get description(){return fa.get(this)?.description},get _def(){return this._zod.def}}),zs=/*@__PURE__*/ y(`_ZodString`,(e,t)=>{pr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r)},/*@__PURE__*/ bt({format:e=>E(e).format??null,minLength:e=>E(e).minimum??null,maxLength:e=>E(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ to(...e))},includes(...e){return this.check(/* @__PURE__ */ io(...e))},startsWith(...e){return this.check(/* @__PURE__ */ ao(...e))},endsWith(...e){return this.check(/* @__PURE__ */ oo(...e))},min(...e){return this.check(/* @__PURE__ */ $a(...e))},max(...e){return this.check(/* @__PURE__ */ Qa(...e))},length(...e){return this.check(/* @__PURE__ */ eo(...e))},nonempty(...e){return this.check(/* @__PURE__ */ $a(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ no(e))},uppercase(e){return this.check(/* @__PURE__ */ ro(e))},trim(){return this.check(/* @__PURE__ */ lo())},normalize(...e){return this.check(/* @__PURE__ */ co(...e))},toLowerCase(){return this.check(/* @__PURE__ */ uo())},toUpperCase(){return this.check(/* @__PURE__ */ fo())},slugify(){return this.check(/* @__PURE__ */ po())}})),Bs=/*@__PURE__*/ y(`ZodString`,(e,t)=>{pr.init(e,t),zs.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ha(Gs,e))},url(e){return this.check(/* @__PURE__ */ xa(Ys,e))},jwt(e){return this.check(/* @__PURE__ */ Ia(dc,e))},emoji(e){return this.check(/* @__PURE__ */ Sa(Zs,e))},guid(e){return this.check(/* @__PURE__ */ ga(Ks,e))},uuid(e){return this.check(/* @__PURE__ */ _a(qs,e))},uuidv4(e){return this.check(/* @__PURE__ */ va(qs,e))},uuidv6(e){return this.check(/* @__PURE__ */ ya(qs,e))},uuidv7(e){return this.check(/* @__PURE__ */ ba(qs,e))},nanoid(e){return this.check(/* @__PURE__ */ Ca(Qs,e))},cuid(e){return this.check(/* @__PURE__ */ wa($s,e))},cuid2(e){return this.check(/* @__PURE__ */ Ta(ec,e))},ulid(e){return this.check(/* @__PURE__ */ Ea(tc,e))},base64(e){return this.check(/* @__PURE__ */ Na(cc,e))},base64url(e){return this.check(/* @__PURE__ */ Pa(lc,e))},xid(e){return this.check(/* @__PURE__ */ Da(nc,e))},ksuid(e){return this.check(/* @__PURE__ */ Oa(rc,e))},ipv4(e){return this.check(/* @__PURE__ */ ka(ic,e))},ipv6(e){return this.check(/* @__PURE__ */ Aa(ac,e))},cidrv4(e){return this.check(/* @__PURE__ */ ja(oc,e))},cidrv6(e){return this.check(/* @__PURE__ */ Ma(sc,e))},e164(e){return this.check(/* @__PURE__ */ Fa(uc,e))},datetime(e){return this.check(/* @__PURE__ */ La(Vs,e))},date(e){return this.check(/* @__PURE__ */ Ra(Hs,e))},time(e){return this.check(/* @__PURE__ */ za(Us,e))},duration(e){return this.check(/* @__PURE__ */ Ba(Ws,e))}});function k(e){return/* @__PURE__ */ ma(Bs,e)}let A=/*@__PURE__*/ y(`ZodStringFormat`,(e,t)=>{C.init(e,t),zs.init(e,t)}),Vs=/*@__PURE__*/ y(`ZodISODateTime`,(e,t)=>{Mr.init(e,t),A.init(e,t)}),Hs=/*@__PURE__*/ y(`ZodISODate`,(e,t)=>{Nr.init(e,t),A.init(e,t)}),Us=/*@__PURE__*/ y(`ZodISOTime`,(e,t)=>{Pr.init(e,t),A.init(e,t)}),Ws=/*@__PURE__*/ y(`ZodISODuration`,(e,t)=>{Fr.init(e,t),A.init(e,t)}),Gs=/*@__PURE__*/ y(`ZodEmail`,(e,t)=>{gr.init(e,t),A.init(e,t)}),Ks=/*@__PURE__*/ y(`ZodGUID`,(e,t)=>{mr.init(e,t),A.init(e,t)}),qs=/*@__PURE__*/ y(`ZodUUID`,(e,t)=>{hr.init(e,t),A.init(e,t)});function Js(e){return/* @__PURE__ */ _a(qs,e)}let Ys=/*@__PURE__*/ y(`ZodURL`,(e,t)=>{wr.init(e,t),A.init(e,t)});function Xs(e){return/* @__PURE__ */ xa(Ys,e)}let Zs=/*@__PURE__*/ y(`ZodEmoji`,(e,t)=>{Tr.init(e,t),A.init(e,t)}),Qs=/*@__PURE__*/ y(`ZodNanoID`,(e,t)=>{Er.init(e,t),A.init(e,t)}),$s=/*@__PURE__*/ y(`ZodCUID`,(e,t)=>{Dr.init(e,t),A.init(e,t)}),ec=/*@__PURE__*/ y(`ZodCUID2`,(e,t)=>{Or.init(e,t),A.init(e,t)}),tc=/*@__PURE__*/ y(`ZodULID`,(e,t)=>{kr.init(e,t),A.init(e,t)}),nc=/*@__PURE__*/ y(`ZodXID`,(e,t)=>{Ar.init(e,t),A.init(e,t)}),rc=/*@__PURE__*/ y(`ZodKSUID`,(e,t)=>{jr.init(e,t),A.init(e,t)}),ic=/*@__PURE__*/ y(`ZodIPv4`,(e,t)=>{Ir.init(e,t),A.init(e,t)}),ac=/*@__PURE__*/ y(`ZodIPv6`,(e,t)=>{zr.init(e,t),A.init(e,t)}),oc=/*@__PURE__*/ y(`ZodCIDRv4`,(e,t)=>{Br.init(e,t),A.init(e,t)}),sc=/*@__PURE__*/ y(`ZodCIDRv6`,(e,t)=>{Hr.init(e,t),A.init(e,t)}),cc=/*@__PURE__*/ y(`ZodBase64`,(e,t)=>{Gr.init(e,t),A.init(e,t)}),lc=/*@__PURE__*/ y(`ZodBase64URL`,(e,t)=>{Jr.init(e,t),A.init(e,t)}),uc=/*@__PURE__*/ y(`ZodE164`,(e,t)=>{Yr.init(e,t),A.init(e,t)}),dc=/*@__PURE__*/ y(`ZodJWT`,(e,t)=>{Zr.init(e,t),A.init(e,t)}),fc=/*@__PURE__*/ y(`ZodNumber`,(e,t)=>{Qr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jo(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ bt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=E(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=E(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=E(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>E(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},min(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},lt(e,t){return this.check(/* @__PURE__ */ qa(e,t))},lte(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},max(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},int(e){return this.check(M(e))},safe(e){return this.check(M(e))},positive(e){return this.check(/* @__PURE__ */ Ya(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Xa(0,e))},negative(e){return this.check(/* @__PURE__ */ qa(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ Ja(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Za(e,t))},step(e,t){return this.check(/* @__PURE__ */ Za(e,t))},finite(){return this}}));function j(e){return/* @__PURE__ */ Va(fc,e)}let pc=/*@__PURE__*/ y(`ZodNumberFormat`,(e,t)=>{$r.init(e,t),fc.init(e,t)});function M(e){return/* @__PURE__ */ Ha(pc,e)}let mc=/*@__PURE__*/ y(`ZodBoolean`,(e,t)=>{ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r)});function N(e){return/* @__PURE__ */ Ua(mc,e)}let hc=/*@__PURE__*/ y(`ZodNull`,(e,t)=>{ti.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r)});function gc(e){return/* @__PURE__ */ Wa(hc,e)}let _c=/*@__PURE__*/ y(`ZodUnknown`,(e,t)=>{ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function vc(){return/* @__PURE__ */ Ga(_c)}let yc=/*@__PURE__*/ y(`ZodNever`,(e,t)=>{ri.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r)});function bc(e){return/* @__PURE__ */ Ka(yc,e)}let xc=/*@__PURE__*/ y(`ZodArray`,(e,t)=>{Rs(),si.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ $a(e,t))},nonempty(e){return this.check(/* @__PURE__ */ $a(1,e))},max(e,t){return this.check(/* @__PURE__ */ Qa(e,t))},length(e,t){return this.check(/* @__PURE__ */ eo(e,t))},unwrap(){return this.element}});function P(e,t){return/* @__PURE__ */ mo(xc,e,t)}let Sc=/*@__PURE__*/ y(`ZodObject`,(e,t)=>{Rs(),pi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),Et(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(h(this._zod.def,{catchall:e}))},passthrough(){return this.clone(h(this._zod.def,{catchall:vc()}))},loose(){return this.clone(h(this._zod.def,{catchall:vc()}))},strict(){return this.clone(h(this._zod.def,{catchall:bc()}))},strip(){return this.clone(h(this._zod.def,{catchall:void 0}))},extend(e){return et(this,e)},safeExtend(e){return nt(this,e)},merge(e){return rt(this,e)},pick(e){return Ze(this,e)},omit(e){return $e(this,e)},partial(...e){return it(Pc,this,e[0])},exactPartial(...e){return it(Ic,this,e[0],`exactPartial`)},required(...e){return at(Wc,this,e[0])}});function F(e,t){let n={type:`object`,shape:e??{},...g(t)};return new Sc(n)}function I(e,t){return new Sc({type:`object`,shape:e,catchall:bc(),...g(t)})}let Cc=/*@__PURE__*/ y(`ZodUnion`,(e,t)=>{hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.options=t.options});function L(e,t){return new Cc({type:`union`,options:e,...g(t)})}let wc=/*@__PURE__*/ y(`ZodDiscriminatedUnion`,(e,t)=>{Cc.init(e,t),_i.init(e,t)});function R(e,t,n){return new wc({type:`union`,options:t,discriminator:e,...g(n)})}let Tc=/*@__PURE__*/ y(`ZodIntersection`,(e,t)=>{vi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)});function Ec(e,t){return new Tc({type:`intersection`,left:e,right:t})}let Dc=/*@__PURE__*/ y(`ZodTuple`,(e,t)=>{Rs(),xi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ss(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Pc({type:`optional`,innerType:e}))})}});function Oc(e,t,n){let r=t instanceof S;return new Dc({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let kc=/*@__PURE__*/ y(`ZodRecord`,(e,t)=>{Rs(),Ti.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return!t||!t._zod?new kc({type:`record`,keyType:k(),valueType:e,...g(t)}):new kc({type:`record`,keyType:e,valueType:t,...g(n)})}let Ac=/*@__PURE__*/ y(`ZodEnum`,(e,t)=>{Ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];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 Ac({...t,checks:[],...g(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 Ac({...t,checks:[],...g(r),entries:i})}});function B(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ac({type:`enum`,entries:n,...g(t)})}let jc=/*@__PURE__*/ y(`ZodLiteral`,(e,t)=>{Di.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(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 V(e,t){return new jc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let Mc=/*@__PURE__*/ y(`ZodTransform`,(e,t)=>{Rs(),Oi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Pt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(gt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(gt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Nc(e){return new Mc({type:`transform`,transform:e})}let Pc=/*@__PURE__*/ y(`ZodOptional`,(e,t)=>{Ai.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Fc(e){return new Pc({type:`optional`,innerType:e})}let Ic=/*@__PURE__*/ y(`ZodExactOptional`,(e,t)=>{ji.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Lc(e){return new Ic({type:`optional`,innerType:e})}let Rc=/*@__PURE__*/ y(`ZodNullable`,(e,t)=>{Mi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function zc(e){return new Rc({type:`nullable`,innerType:e})}let Bc=/*@__PURE__*/ y(`ZodDefault`,(e,t)=>{Ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Vc(e,t){return new Bc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Hc=/*@__PURE__*/ y(`ZodPrefault`,(e,t)=>{Fi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Uc(e,t){return new Hc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Wc=/*@__PURE__*/ y(`ZodNonOptional`,(e,t)=>{Ii.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ps(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Gc(e,t){return new Wc({type:`nonoptional`,innerType:e,...g(t)})}let Kc=/*@__PURE__*/ y(`ZodCatch`,(e,t)=>{zi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function qc(e,t){return new Kc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Dt(t)})}let Jc=/*@__PURE__*/ y(`ZodPipe`,(e,t)=>{Bi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.in=t.in,e.out=t.out});function Yc(e,t){return new Jc({type:`pipe`,in:e,out:t})}let Xc=/*@__PURE__*/ y(`ZodReadonly`,(e,t)=>{Hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Zc(e){return new Xc({type:`readonly`,innerType:e})}let Qc=/*@__PURE__*/ y(`ZodLazy`,(e,t)=>{Wi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ss(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function $c(e){return new Qc({type:`lazy`,getter:e})}let el=/*@__PURE__*/ y(`ZodCustom`,(e,t)=>{Gi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r)});function tl(e,t){return/* @__PURE__ */ ho(el,e??(()=>!0),t)}function nl(e,t={}){return/* @__PURE__ */ go(el,e,t)}function rl(e,t){return/* @__PURE__ */ _o(e,t)}function il(e){return/* @__PURE__ */ La(Vs,e)}function al(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 ol=L([k(),j(),N(),gc()]);function sl(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 cl=tl(sl,{message:`JSON value must not contain circular references`}),ll=$c(()=>L([ol,P(ll),z(k(),ll)])),H=cl.pipe(ll);cl.pipe(P(ll));let ul=cl.pipe(z(k(),ll)),dl=I({code:k().min(1),message:k().min(1),retryable:N(),diagnostic:k().min(1).optional(),stage:k().min(1).optional(),durationMs:j().int().nonnegative().optional(),stderrTail:k().min(1).optional()}).superRefine(al([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),fl=k().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),pl=e=>k().min(1).max(e).refine(e=>e.trim().length>0),ml=z(fl,F({label:pl(256).optional(),description:pl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),hl=z(fl,pl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),gl=k().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),U=gl.brand(),W=gl.brand(),_l=gl.brand();gl.brand(),gl.brand();let vl=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),yl=vl.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),bl=F({modes:P(F({id:yl,label:vl.max(256),description:vl.max(1024).optional(),dangerous:N().optional(),localizations:ml.optional()}).strict()).min(1).max(32),defaultModeId:yl}).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`]})});F({threadId:W,permissionModeId:yl}).strict();let xl=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`});F({sourceThreadId:W,lastTurnId:_l.optional(),targetHarnessId:U,targetModel:xl.max(1024).optional(),targetThinkingOptionId:xl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).optional()}).strict();let Sl=F({sourceThreadId:W,sourceHarnessId:U,sourceHarnessLabel:xl.max(256).optional(),sourceModel:xl.max(1024).optional(),targetHarnessId:U,targetHarnessLabel:xl.max(256).optional(),targetModel:xl.max(1024).optional(),totalTurns:j().int().min(1),boundaryTurnNumber:j().int().min(1),includedTurnNumbers:P(j().int().min(1)),omittedTurns:j().int().min(0),preview:k().max(32e3),createdAtMs:j().int().nonnegative()}).strict();F({threadId:W,handoff:Sl}).strict();let G=j().int().safe().nonnegative(),Cl=j().finite().nonnegative(),wl=j().finite().min(0).max(100),Tl=F({version:L([V(3),V(4)]).optional(),requestId:k().min(1),turnId:k().min(1).max(1024),outputTokens:G,startedAtMs:G,completedAtMs:G}).strict().refine(e=>e.completedAtMs>e.startedAtMs),El=F({version:L([V(2),V(3),V(4)]).optional(),value:Cl,turnId:k().min(1).max(1024),at:G}).strict();F({outputTimings:P(Tl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:El.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:El.extend({value:G}).optional()}).strict();let Dl=e=>hl.refine(t=>Object.values(t).every(t=>t.length<=e)),Ol=F({composerIndicators:P(F({kind:V(`countdown`),id:k().min(1).max(64),expiresAtUnix:G,label:Dl(256).optional(),tooltip:Dl(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:G.optional(),cachedInputTokens:G.optional(),cacheWriteInputTokens:G.optional(),outputTokens:G.optional(),outputTokensPerSecond:Cl.optional(),sessionOutputTokensPerSecond:Cl.optional(),apiOutputTokensPerSecond:Cl.optional(),reasoningOutputTokens:G.optional(),totalTokens:G.optional(),totalCostUsd:Cl.optional(),totalCredits:Cl.optional(),contextUsagePercent:Cl.optional(),cacheHitRatePercent:wl.optional(),contextWindowTokens:G.optional(),contextUsedTokens:G.optional(),planFiveHourUsedPercent:wl.optional(),planFiveHourResetsAtUnix:G.optional(),planSevenDayUsedPercent:wl.optional(),planSevenDayResetsAtUnix:G.optional(),sessionCacheHitRatePercent:wl.optional(),timeToFirstOutputMs:G.optional(),latestRequestTimeToFirstOutputMs:G.optional(),costSource:B([`publicPrice`,`native`]).optional(),unpricedModels:P(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`]})}),kl=j().finite().min(0).max(100),Al=B([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),jl=F({id:k().min(1).max(256),label:k().min(1).max(256),localizations:ml.optional()}).strict(),Ml=F({product:k().min(1),periodType:Al.optional(),scope:jl.optional(),localizations:ml.optional(),used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),usagePercent:kl,resetsAt:k().min(1).optional()}).strict(),Nl=F({availableCount:j().int().safe().positive(),nextExpiresAt:k().min(1).optional(),expiresAt:P(k().min(1)).min(1).max(32).optional()}).strict(),Pl=F({used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),label:k().min(1).optional(),scope:jl.optional(),localizations:ml.optional(),usedPercent:kl,resetsAt:k().min(1).optional(),periodType:Al,productUsage:P(Ml).min(1).optional(),resetCredits:Nl.optional()}).strict(),Fl=F({amount:j().finite().nonnegative(),currency:k().trim().min(1).max(8),label:k().trim().min(1).max(128).optional()}).strict();F({threadId:W,refresh:V(`exact`).optional()}).strict(),F({threadId:W,usage:Ol.nullable(),accountCredits:Pl.optional(),accountBalance:Fl.optional(),accountCreditsSupported:N().optional()}).strict();let Il=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ll=k().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Rl=B([`priority`,`ultrafast`]),K=F({id:Ll,serviceTier:Rl.optional()}).strict();function zl(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let q=Il.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Bl=Il.max(256),Vl=F({id:q,label:Il.max(256)}).strict(),Hl=F({ref:K,label:Il.max(256),resolvedModelLabel:Bl.optional(),fastModel:K.optional(),supportedThinkingOptionIds:P(q).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function Ul(e,t){if(t)return e?.models.find(e=>zl(e.ref,t)||zl(e.fastModel,t))}let Wl=P(Vl).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)}),Gl=B([`catalog`,`activeModel`]),Kl=F({models:P(Hl),defaultModel:K.optional(),thinkingOptions:Wl,defaultThinkingOptionId:q.optional(),thinkingOptionsScope:Gl.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>zl(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>zl(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!Ul(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),ql=F({fork:N(),forkAcrossCwd:N(),rollbackLastTurn:N()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Jl=B([`live`,`atCreate`]),Yl=F({configuration:F({selectModel:N(),selectThinkingOption:N(),selectPermissionMode:N(),permissionModeScope:Jl.default(`live`)}).strict(),history:ql,subagents:F({observe:N(),readTranscript:N()}).strict().optional(),autonomousTurns:F({observe:N()}).strict().optional(),steer:N().optional(),persistentPlan:N().optional()}).strict();F({effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),availableThinkingOptions:Wl.optional(),effectivePermissionModeId:yl.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 Xl=F({open:V(!0)}).strict();L([F({status:V(`ready`),catalog:Kl,permissionModes:bl.optional(),capabilities:Yl,webUi:Xl.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`]})}),F({status:B([`notInstalled`,`unavailable`,`error`]),error:dl}).strict()]),F({harnessId:U,cwd:Il.max(16384).optional(),refresh:N().optional(),purpose:V(`availability`).optional(),credentialAccess:B([`allow`,`retry`]).optional()}).strict(),F({harnessId:U}).strict(),F({}).strict(),F({threadId:W,model:K}).strict(),F({threadId:W,thinkingOptionId:q}).strict(),F({threadId:W,includeReferenceCapability:N().optional()}).strict(),R(`owner`,[F({owner:V(`codex`),locked:N(),effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),effectivePermissionModeId:yl.optional(),history:ql.optional(),supportsThreadReferences:V(!0).optional(),handoff:Sl.optional()}).strict(),F({owner:V(`external`),harnessId:Il.max(256),transportModelId:Il.max(8192),effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),availableThinkingOptions:Wl.optional(),effectivePermissionModeId:yl.optional(),catalog:Kl.optional(),history:ql,usage:Ol.optional(),handoff:Sl.optional(),locked:V(!0)}).strict()]),F({threadIds:P(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 Zl=R(`owner`,[F({threadId:W,owner:V(`codex`)}).strict(),F({threadId:W,owner:V(`external`),harnessId:k().max(256).pipe(U)}).strict()]);F({threads:P(Zl).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)}),F({threadId:W,text:k().optional()}).strict(),F({kind:V(`application`),value:k().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),kt}}).pipe(F({expectedTurnId:_l,clientUserMessageId:k().min(1),delivery:B([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),B([`activeTurn`,`newTurn`]),F({delivery:B([`official`,`activeTurn`,`newTurn`])}).strict();let Ql=k().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),$l=Ql.pipe(U),eu=$l.refine(e=>e!==`codex`,`The official Codex identity is reserved`),tu=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`),nu=Xs().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),ru=F({en:k().max(4096),"zh-CN":k().max(4096).optional()}).strict(),iu=F({commands:P(F({terminal:k().max(256),command:k().max(4096)}).strict()).max(8),before:ru.optional(),after:ru.optional(),downloads:P(F({label:k().max(128),url:nu}).strict()).max(8).optional()}).strict(),au={id:$l,name:k().trim().min(1).max(128),version:k().min(1).max(128),kind:V(`usage`).optional(),iconStyle:F({vector:F({viewBox:k().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:P(F({d:k().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:B([`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:iu.optional(),notice:ru.optional(),launchCommand:V(!0).optional(),links:F({website:nu.optional(),documentation:nu.optional(),installation:nu.optional()}).strict().optional()};F({manifestVersion:V(1),...au,adapterApiVersion:j().int().positive(),entry:tu,icon:tu.optional()}).strict();let ou=k().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),su=F({...au,icon:ou.optional()}).strict();F({}).strict(),F({plugins:P(su.extend({id:eu})).max(128)}).strict(),F({version:V(1),enabled:P($l).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let cu=131072,lu=Ql,uu=B([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),du=B([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),fu=k().trim().min(1).max(128);function pu(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let mu=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),hu=tu.refine(e=>pu(e)!==void 0&&mu(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),gu=k().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Xs({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function _u(e){return I({en:e,"zh-CN":e})}let vu=_u(k().trim().min(1)),yu=P(du).max(du.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),bu=P(uu).max(uu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),xu={key:k().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:vu,description:vu.optional()},Su={...xu,step:j().positive().optional(),default:j().optional()},Cu=I({value:k(),label:vu}),wu=R(`type`,[I({...xu,type:V(`boolean`),default:N().optional()}),I({...xu,type:V(`string`),placeholder:vu.optional(),default:k().optional()}),I({...Su,type:V(`number`),min:j().optional(),max:j().optional()}),I({...Su,type:V(`range`),min:j(),max:j()}),I({...xu,type:V(`select`),options:P(Cu).min(1),default:k().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),Tu=F({manifestVersion:M().positive(),id:lu,name:L([fu,_u(fu)]),version:k().min(1).max(128),desktopApi:M().positive()}).passthrough().extend({manifestVersion:V(1),desktopApi:V(1),description:I({en:k().max(4096),"zh-CN":k().max(4096).optional()}).optional(),author:k().trim().min(1).max(128).optional(),repository:gu.optional(),details:I({en:k().max(16384),"zh-CN":k().max(16384).optional()}).optional(),icon:hu.optional(),screenshots:P(hu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:I({script:tu,style:tu.optional()}).optional(),backend:I({script:tu.refine(mu)}).optional(),slots:bu.default(()=>[]),settingsSchema:P(wu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:yu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),Eu=k().regex(/^[a-f0-9]{64}$/u),Du=I({state:B([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:Eu.optional(),error:k().optional(),conflictWith:lu.optional()});I({controllerPid:M().positive(),targetId:k().nullable(),updatedAt:il(),handledReloadToken:Js().optional(),extensions:z(k(),Du),surfaces:z(k(),Du).optional()});let Ou=B([`official`,`community`]);function ku(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Au=gu.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||ku(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),ju=I({id:lu,version:k().trim().min(1).max(128),name:vu.extend({en:fu,"zh-CN":fu}),description:_u(k().trim().min(1).max(4096)),details:_u(k().trim().min(1).max(16384)).optional(),author:k().trim().min(1).max(128),repository:gu,stars:j().int().min(0).optional(),downloads:j().int().min(0).optional(),categories:yu.optional(),trustTier:Ou.default(`community`),icon:gu.optional(),screenshots:P(gu).max(4).optional(),downloadUrl:Au,sha256:Eu,slots:bu.optional(),publishedAt:k().optional(),updatedAt:k().optional(),minCodexHostVersion:k().optional()});I({schemaVersion:V(1),generatedAt:k(),extensions:P(ju).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Mu=k().trim().min(1).max(128),Nu=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,Pu=lu.refine(e=>!Nu.test(e),`Reserved extension ID`),Fu=B([`desktop`,`web`]),Iu=Eu,Lu=Js(),Ru=tu.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Nu.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),zu=Tu.shape,Bu=(e,t=0)=>I({en:k().trim().min(t).max(e),"zh-CN":k().trim().min(t).max(e)}),Vu=e=>Ru.refine(t=>t.endsWith(e),`Expected a ${e} file`),Hu=Vu(`.mjs`),Uu=Vu(`.css`).optional(),Wu=e=>e.normalize(`NFC`).toLowerCase(),Gu=I({manifestVersion:V(2),id:Pu,name:Bu(128,1),version:k().trim().min(1).max(128),description:Bu(4096),details:Bu(16384).optional(),author:zu.author,repository:zu.repository,icon:zu.icon.refine(e=>e===void 0||Ru.safeParse(e).success),screenshots:zu.screenshots.refine(e=>e===void 0||e.every(e=>Ru.safeParse(e).success)),categories:zu.categories,settingsSchema:zu.settingsSchema,slots:zu.slots.removeDefault().optional(),page:I({apiVersion:V(1),entry:Hu,style:Uu,title:Bu(128,1).optional()}).optional(),widget:I({apiVersion:V(1),entry:Hu,style:Uu}).optional(),desktop:I({apiVersion:V(1),script:Vu(`.js`),style:Uu}).optional(),web:I({apiVersion:V(1),entry:Hu.optional(),style:Uu}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:I({apiVersion:V(1),entry:Hu}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||Wu(e)!==Wu(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Ku({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let qu=Mu,Ju=B([`running`,`waiting`,`idle`,`unknown`]),Yu=I({sourceThreadId:W,createdAtMs:j().int().nonnegative()}),Xu=I({harnessId:U,title:k().optional(),status:Ju,archived:N(),updatedAtMs:j().int().nonnegative().optional()}),Zu=I({revision:M().nonnegative(),parents:z(W,W),handoffs:z(W,Yu).optional(),nodes:z(W,Xu),truncated:N()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,handoffs:t,nodes:n})=>Object.entries(e).every(([e,t])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t))&&Object.entries(t??{}).every(([e,{sourceThreadId:t}])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t)),`Missing Thread tree node`),Qu=k().min(1).max(128);I({});let $u=I({subscriptionId:Qu});I({}),$u.extend({snapshot:Zu});let ed=M().nonnegative(),td=I({revision:ed,enabled:P(Pu).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});I({version:V(1),seeded:P(Pu).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});let nd=F({version:k().trim().min(1).max(128),publishedAt:k().trim().min(1).max(64).optional(),notes:k().trim().min(1).max(8192),url:gu.optional()}),{downloadUrl:rd,...id}=ju.shape,ad=F({...id,id:Pu,format:V(`codexhost`),targets:P(Fu).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:I({page:M().positive().optional(),widget:M().positive().optional(),desktop:M().positive().optional(),web:M().positive().optional(),backend:M().positive().optional()}),downloadUrl:rd.refine(e=>e.startsWith(`https://`),`Expected HTTPS`),featured:N().optional(),featuredOrder:M().nonnegative().optional(),changelog:P(nd).max(20).optional()}).refine(({targets:e,apis:t})=>{let n=Ku({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);F({schemaVersion:V(2),generatedAt:k().min(1),extensions:P(ad).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:gu,fetchedAt:il(),cached:N(),stale:N().optional()});let od={id:Pu},sd={...od,activationId:Lu,digest:Iu},cd={...od,activationId:sd.activationId.optional()},ld=k().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),ud=k().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function dd(e){return k().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let fd=I({type:V(`github`),repository:k().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:ud.optional(),tag:ud.optional(),asset:k().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Ru.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),pd=L([I({type:V(`catalog`),...od}),fd,I({type:V(`zip`),base64:dd(67108864).min(4)}),I({type:V(`zip`),localZipPath:ld}),I({type:V(`localDir`),localDir:ld})]),md=R(`type`,[I({type:V(`catalog`),...od}),fd,I({type:V(`zip`)}),I({type:V(`localDir`)})]),hd=I({...sd,manifest:Gu,installedAt:il(),source:md.optional()}),gd=e=>k().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),_d={desktopConflictWith:Pu.optional()},vd=B([`none`,`inactive`,`starting`,`running`,`failed`]),yd=R(`state`,[hd.extend({state:V(`valid`),enabled:N(),..._d,iconDataUrl:gd(cu).optional(),screenshotDataUrls:P(gd(524288)).max(4).optional(),backendState:vd.optional(),backendError:k().optional()}),I({state:B([`invalid`,`incompatible`]),id:k().min(1),enabled:N(),error:k()})]);I({revision:ed,configuration:td,diagnostics:P(k()),extensions:P(yd)}),I({revision:ed,extensions:P(hd.extend({..._d,settingsRevision:ed})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,catalogIcon:`codexhost/extensions/catalogIcon`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`,threadTree:`codexhost/extensions/threadTree`},bd=Object.freeze(Object.values(J));new Set(bd),I({});let xd={expectedRevision:ed};I({...od,...xd}),hd.extend({replaced:N()}),R(`state`,[I({state:V(`saved`),configuration:td}),I({state:V(`revision-conflict`),revision:ed})]),I({...cd,digest:sd.digest.optional(),path:Ru}),I({mimeType:k().min(1),base64:dd(16777216),digest:sd.digest}),I({mimeType:B([`image/png`,`image/jpeg`,`image/webp`]),base64:dd(cu)}),I({settingsRevision:ed,values:ul}),J.list,J.snapshot,J.catalog,I({forceRefresh:N().optional(),staleWhileRevalidate:N().optional()}),J.catalogIcon,I({...od}),J.install,I({source:pd}),J.update,I({...od,expectedDigest:sd.digest,expectedActivationId:sd.activationId.optional(),source:pd.optional()}),J.enable,J.disable,J.uninstall,I({...od,removeData:N().optional(),expectedDigest:sd.digest.optional()}),I({...od,removed:N()}),J.recover,I({expectedRevision:xd.expectedRevision.optional()}),J.asset,J.settingsGet,I(cd),J.settingsSet,I({...cd,expectedSettingsRevision:ed,values:ul}),J.backendInvoke,I({...cd,method:qu,params:H.optional()}),I({result:H}),J.threadTree,F({threadId:W}).strict(),F({confirmed:N()}).strict();let Sd=[`codex-desktop`,`web`,`web-desktop-shell`,`web-mobile`,`ssh-remote`,`cli`],Cd=[`darwin`,`win32`,`linux`],wd=[`arm64`,`x64`,`ia32`,`arm`],Td=[`zh`,`en`,`ja`,`ko`,`de`,`fr`,`es`,`pt`,`ru`,`other`],Ed=[`codex`,`claude-code`,`antigravity`,`pi`,`opencode`,`cursor-cli`,`deepseek-harness`,`grok`,`omp`,`qwen-code`,`kiro-cli`,`codebuddy`,`workbuddy`,`devin`,`hermes`,`qoder`,`qoder-cn`,`kimi-code`,`zcode`,`copilot`,`custom`],Dd=[`official-relay`,`self-hosted-relay`,`tailscale-serve`,`tailscale-funnel`,`tailscale-ip`,`lan`,`custom-proxy`,`remote-peer`],Od=k().min(1).max(40).regex(/^[0-9A-Za-z._+-]+$/u),kd=B(Sd),Ad=B(Td),jd=B(Ed),Md=B(Dd);new Set(Ed),new Set(Td),F({enabled:N(),forcedOffByEnv:N()}).strict(),F({enabled:N()}).strict(),F({surfaces:P(kd).max(12).optional(),harnesses:P(jd).max(32).optional(),remoteAccess:P(Md).max(12).optional()}).strict(),F({dailyActive:V(!0).optional(),weeklyActive:V(!0).optional(),monthlyActive:V(!0).optional(),newInstall:V(!0).optional(),retainedD1:V(!0).optional(),retainedD7:V(!0).optional(),remoteAny:V(!0).optional(),appVersion:Od.optional(),codexDesktopVersion:Od.optional(),os:B(Cd).optional(),arch:B(wd).optional(),uiLanguage:Ad.optional(),surfaces:P(kd).min(1).max(12).optional(),harnesses:P(jd).min(1).max(32).optional(),remoteAccess:P(Md).min(1).max(12).optional()}).strict().refine(e=>Object.keys(e).length>0,{message:`Telemetry heartbeat must contain at least one countable field`}),[...bd],F({sections:P(F({id:k().min(1),name:k().min(1),threads:P(ul)}).strict())}).strict(),F({threadId:k().min(1).max(1024),sectionId:k().min(1).max(1024).nullable()}).strict(),F({threadIds:P(k().min(1))}).strict(),F({threadId:k().min(1).max(1024),pinned:N()}).strict(),F({}).strict(),F({parents:z(k().min(1),k().min(1))}).strict(),F({prompt:k().max(16384).optional()}).strict(),F({projects:P(F({id:k(),name:k(),rootPaths:P(k()),createdAt:j().int().optional()})),nativeProjects:V(!0).optional(),assignments:z(k(),k()),projectless:P(k()),pinned:P(k()),sectionProjects:z(k(),P(k())).optional(),pinnedProjects:P(k()).optional()});let Nd=z(k(),vc()),Pd=F({epoch:k().uuid(),sequence:j().int().nonnegative()});R(`type`,[F({type:V(`projects-changed`),cursor:Pd}),F({type:V(`skills-changed`),cursor:Pd,cwd:k().optional()}),F({type:V(`harness-inspection-changed`),cursor:Pd,harnessId:k().min(1)}),F({type:V(`display-settings-changed`),cursor:Pd}),F({type:V(`preferences-changed`),cursor:Pd,revision:j().int().nonnegative()}),F({type:V(`extensions-changed`),cursor:Pd,revision:ed}),F({type:V(`hello`),version:V(1),cursor:Pd,reset:N()}),F({type:V(`changed`),cursor:Pd,threadId:k().min(1),method:k().min(1)})]);let Fd=R(`type`,[F({type:V(`text`),id:k(),prompt:k(),secret:N().optional(),optional:N().optional()}),F({type:V(`choice`),id:k(),prompt:k(),multiple:N(),allowOther:N(),optional:N().optional(),options:P(F({value:k(),label:k(),description:k().optional()}))})]),Id=R(`type`,[F({type:V(`approval`),title:k(),description:k().optional(),subject:vc().optional(),actions:P(F({id:k(),label:k(),effect:k()}))}),F({type:V(`question`),title:k().optional(),questions:P(Fd)})]),Ld=F({requestId:L([k(),j().int()]),threadId:k(),kind:B([`approval`,`question`]),interaction:Id,request:Nd}),Rd=F({id:k().min(1),clientUserMessageId:k().min(1),input:P(Nd),presentationInput:P(Nd).nullable().optional()}).passthrough();F({fields:P(F({path:P(L([k(),j().int().nonnegative()])),originalLength:j().int().nonnegative()}))});let zd=F({id:k().min(1),status:k().min(1),codexhostTurnOutcome:F({status:V(`unknown`),reason:k()}).optional(),items:P(F({id:k().min(1),type:k().min(1)}).passthrough()),codexhostFileOperations:P(F({beforeItemId:k().nullable(),item:F({id:k().min(1),type:k().min(1)}).passthrough()})).optional(),error:F({message:k().optional()}).passthrough().nullable().optional(),fingerprint:k().min(1).optional(),unchanged:V(!0).optional()}).passthrough(),Bd=F({id:k().min(1).max(512),fingerprint:k().min(1).max(128)});F({threadId:k().min(1),knownTurns:P(Bd).max(64).optional(),truncateToolOutput:N().optional()});let Vd=F({harnessId:k().min(1),nativeSessionId:k().min(1)});F({cursor:Pd,activeTurnId:k().min(1).nullable().optional(),command:F({name:k().min(1),turn:zd,subsequentTurnId:k().min(1).optional()}).optional(),thread:F({id:k().min(1),cwd:k(),modelProvider:k().min(1),createdAt:j(),updatedAt:j(),recencyAt:j().nullable().optional(),status:F({type:k()}).passthrough(),name:k().nullable().optional(),preview:k().optional(),codexhostImportSource:Vd.optional(),turns:P(zd).length(0)}).passthrough(),turnsPage:F({data:P(zd).max(5),nextCursor:k().nullable()}),configuration:F({native:F({model:k().min(1).max(1024).optional(),reasoningEffort:k().min(1).max(128).optional()}).optional(),effectiveModel:K.optional(),effectiveThinkingOptionId:q.optional(),effectivePermissionModeId:yl.optional()}),queue:F({items:P(Rd),pausedReason:B([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:P(Ld),handoff:Sl.optional()}),F({version:V(1),owner:V(`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(),capabilities:F({peerDelegation:V(1).optional()}).optional()}),F({epoch:k().uuid(),threadId:k().min(1),requestId:L([k(),j().int()]),result:Nd}),F({includeArchived:N().optional(),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional(),scope:L([F({cwd:k().min(1).max(4096),excludeCwds:P(k().min(1).max(4096)).max(1024)}).strict(),F({projectId:k().min(1).max(1024),legacyThreadIds:P(k().min(1).max(1024)).max(1024),rootPaths:P(k().min(1).max(4096)).max(1024).optional()}).strict()]).optional()}).strict(),F({threads:P(ul),ownership:P(Zl),archivedThreadIds:P(W),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional()}).strict(),su.pick({id:!0,name:!0,icon:!0,iconStyle:!0});let Hd=I({threadId:k().max(1024),title:k().max(240),project:k().max(240),harness:I({id:k().min(1).max(128),name:k().min(1).max(128)}).optional(),state:B([`idle`,`running`,`waiting`,`completed`,`failed`]),updatedAt:j().nonnegative()});I({epoch:k().max(128),revision:M().nonnegative(),running:M().nonnegative(),waiting:M().nonnegative(),sessions:P(Hd).max(32).default([]),notifications:P(I({threadId:k().max(1024),key:k().max(4096),kind:B([`completed`,`failed`,`approval`,`question`]),revision:M().nonnegative()})).max(256)});let Ud=k().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);F({available:N()}).strict(),F({path:k().min(1),mimeType:Ud}).strict();let Wd=B([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);R(`ok`,[F({ok:V(!0),text:k()}).strict(),F({ok:V(!1),error:F({code:Wd}).strict()}).strict()]),F({threadId:W.optional(),cwd:k().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Gd=F({name:k().min(1).regex(/^[^\s[\]]+$/u),description:k().optional(),path:k().min(1),scope:B([`project`,`global`]),source:k().min(1)}).strict();F({revision:j().int().nonnegative(),complete:N(),skills:P(Gd),warnings:P(k()).optional()}).strict(),F({cwd:k().min(1).optional()}).strict();let Kd=F({kind:B([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:k().min(1)}).strict(),qd=R(`status`,[F({status:V(`not-installed`)}),F({status:V(`not-running`)}),F({status:V(`not-logged-in`)}),F({status:V(`https-disabled`)}),F({status:V(`not-serving`),command:k()}),F({status:V(`occupied`),target:k()}),F({status:V(`serving`),url:k(),funnel:N()}),F({status:V(`error`),message:k()})]);F({state:qd,error:k().optional()}).strict();let Jd=R(`status`,[F({status:V(`on`)}),F({status:V(`off`)}),F({status:V(`invalid`),reason:k()})]),Yd=F({lan:N(),autostart:Jd}).strict(),Xd=F({expiresAt:k().optional(),issuing:N(),failure:F({detail:k().optional(),retryAt:k(),paused:N()}).optional()}),Zd=R(`status`,[F({status:V(`off`),reason:B([`invite`,`name-taken`,`banned`]).optional()}),F({status:V(`connecting`),reason:B([`full`,`unreachable`]).optional()}),F({status:V(`connected`),url:k(),certificate:Xd}),F({status:V(`missing-certificate`),url:k(),certificate:Xd}),F({status:V(`stopped`),reason:B([`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 Qd=B([`official`,`self-hosted`]);F({secret:k().min(1),lastUsedAt:j().nullable(),networkUrls:P(Kd),directCandidates:P(Kd).optional(),tailscale:qd,background:Yd.optional(),relay:F({state:Zd,enabled:N(),kind:Qd,officialHost:k(),customHost:k().optional(),officialHostname:k().optional(),customHostname:k().optional(),quotaUntil:k().optional()}).strict().optional()}).strict();let $d=I({threadId:k().min(1).max(1024),view:B([`result`,`messages`]),from:j().int().min(1).max(2**53-1).optional(),to:j().int().min(1).max(2**53-1).optional()}),ef=/^[a-zA-Z0-9_-]{1,64}$/u,Y=k().regex(ef),tf=k().regex(ef),nf=k().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),rf=B([`relay`,`tailscale`,`lan`,`custom`]),af=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],of=B(af);new Set(af);let sf=B([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]),cf=F({peerId:Y,hostId:nf,nodeId:tf.optional(),name:k().min(1).max(120),color:of.optional(),origin:k().min(1).max(2048),transportKind:rf,encrypted:N(),enabled:N(),state:sf,supportsPeerPairing:N().optional(),pairedBack:N().optional(),linkedPeerIds:P(Y).max(128).optional(),latencyMs:j().int().nonnegative().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),lastError:k().max(1e3).optional(),projectCount:j().int().nonnegative(),createdAt:k(),updatedAt:k()});F({localPlatform:k().max(64).optional(),peers:P(cf)}),F({connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),name:k().trim().min(1).max(120).optional(),color:of.optional(),pairBack:N().optional(),meshPeerIds:P(Y).max(64).optional(),selfOrigin:k().min(1).max(2048).optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),I({origin:k().min(1).max(2048),token:k().min(1).max(2048),name:k().trim().min(1).max(120).optional(),color:of.optional(),expectedNodeId:tf.optional()}),F({status:B([`added`,`updated`,`existing`]),peerId:Y,hostId:nf,nodeId:tf.optional()});let lf=B([`added`,`updated`,`existing`,`failed`,`skipped`]);F({results:P(F({targetPeerId:Y,targetName:k().min(1).max(120),introducedHost:L([V(`local`),Y]),introducedName:k().min(1).max(120),status:lf,error:k().max(1e3).optional()}))}),F({peerIds:P(Y).max(64).optional(),includeSelf:N().optional(),includeMesh:N().optional(),selfOrigin:k().min(1).max(2048).optional()}),F({peerId:Y,name:k().trim().min(1).max(120).optional(),color:of.nullable().optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),enabled:N().optional()}),F({peerId:Y}),F({removed:N()}),F({peerId:Y.optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let uf=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});F({ok:N(),nodeId:tf.optional(),supportsPeerPairing:N().optional(),pairedBack:N().optional(),latencyMs:j().int().nonnegative().optional(),origin:k().max(2048).optional(),transportKind:rf.optional(),encrypted:N().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),projectCount:j().int().nonnegative().optional(),projects:P(uf).optional(),error:k().max(1e3).optional()});let df=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192),threadIds:P(k().min(1).max(1024))}),ff=F({attachments:V(1).optional(),workspaceFiles:V(1).optional(),officePreview:V(1).optional(),delegation:V(1).optional(),peerPairing:V(1).optional()}),pf=F({version:k().max(128),platform:k().max(64),hostname:k().max(255),homeDir:k().max(4096).optional(),epoch:k().min(1).max(256),nodeId:tf.optional(),peerNodes:z(nf,tf).refine(e=>Object.keys(e).length<=128).optional(),projects:P(df),capabilities:ff.optional()});I({threadId:k().min(1).max(1024),scope:k().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u).optional(),requestId:k().min(1).max(256).optional(),mode:B([`queue`,`steer`]).optional(),expectedTurnId:k().min(1).max(1024).nullable().optional(),content:P(R(`type`,[I({type:V(`text`),text:k()}),I({type:V(`file`),receiptId:k().min(1).max(128)})])).min(1).max(64)});let mf=F({ok:V(!1),error:F({code:k(),message:k(),details:z(k(),vc()).optional()})});L([F({ok:V(!0),value:F({receiptId:k().min(1),file:F({attachmentId:k(),name:k(),bytes:j().int().nonnegative()})})}),mf]),L([F({ok:V(!0),value:F({accepted:V(!0)})}),mf]);let hf=F({name:k().min(1).max(512),path:k().min(1).max(8192),kind:V(`directory`)});F({peerId:Y,path:k().min(1).max(8192).optional()}),F({path:k().min(1).max(8192),parentPath:k().min(1).max(8192).nullable(),homeDir:k().min(1).max(8192).optional(),entries:P(hf)}),F({peerId:Y,parentPath:k().min(1).max(8192),name:k().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),F({path:k().min(1).max(8192),name:k().min(1).max(255)}),F({peerId:Y,path:k().min(1).max(8192),title:k().trim().min(1).max(255).optional()}),F({peerId:Y,workspaceId:k().min(1).max(1024),title:k().trim().min(1).max(255)}),F({peerId:Y,workspaceId:k().min(1).max(1024)}),F({workspaceId:k().min(1).max(1024).optional(),manifest:pf}),F({sessionHostId:k().min(1).max(128).optional()}),F({hosts:P(F({hostId:L([V(`local`),nf]),name:k().min(1).max(120),isLocal:N().optional(),color:of.optional(),hostname:k().max(255).optional()}))}),F({hostId:L([V(`local`),nf])}),F({harnesses:P(F({id:k().regex(/^[a-z0-9][a-z0-9-]*$/u),name:k().min(1).max(120)}))});let gf=B([`listHarnesses`,`inspect`,`start`,`send`,`cancel`,`read`,`answer`,`list`]);I({operation:gf,hopCount:j().int().min(0).max(16),sourceId:Y.optional(),input:ul});let _f=I({code:k().min(1).max(128),message:k().max(4096),details:ul.optional()});L([I({ok:V(!0),value:H}),I({ok:V(!1),error:_f})]);let vf=I({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});I({hosts:P(I({hostId:nf,nodeId:tf.optional(),displayName:k().min(1).max(120),online:N(),state:sf,delegation:N(),projects:P(vf),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional()}))}),I({version:V(1),instanceId:k().min(1).max(128),pid:j().int().positive(),endpoint:k().min(1).max(256),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j().int().nonnegative()}),L([I({operation:V(`hosts`)}),I({operation:gf,hostId:nf,hopCount:j().int().min(0).max(16),timeoutMs:j().int().min(1).max(12e4).optional(),input:ul})]);let yf=F({id:k().min(1).max(256),harnessId:k().min(1),label:k().min(1).max(512),provider:B([`openai-codex`,`xai`])}).strict(),bf=k().regex(/^[a-z][a-z0-9-]{0,47}$/),xf=F({name:bf,source:yf,importedAt:k()}).strict(),Sf=R(`action`,[F({action:V(`list`)}).strict(),F({action:V(`import`),sourceId:k().min(1).max(256),name:bf,confirmed:V(!0)}).strict(),F({action:V(`reimport`),sourceId:k().min(1).max(256),name:bf,confirmed:V(!0)}).strict(),F({action:V(`remove`),name:bf,confirmed:V(!0)}).strict()]),Cf=F({provider:k().min(1).max(128),type:B([`oauth`,`api_key`,`unknown`]),label:k().min(1).max(512).optional(),vendor:B([`openai-codex`,`xai`]).optional()}).strict();F({sources:P(yf),targets:P(F({harnessId:k(),providers:P(B([`openai-codex`,`xai`])),imports:P(xf),others:P(Cf).default([])}).strict())}).strict(),F({targetHarnessId:k().min(1).max(128).optional(),request:Sf}).strict(),F({events:N()});let wf=P(I({agent:k().min(1).max(128),section:B([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);I({entries:wf.nullable()}),I({}),I({entries:wf,initializeOnly:N().optional()});let Tf=I({enabled:N(),timeoutMinutes:j().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let Ef=k().regex(/^external$/u),Df=U.transform(e=>String(e)),Of=I({model:K.optional(),thinkingOptionId:q.optional(),permissionModeId:yl.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),kf=I({lastHarness:U.optional(),byHarness:z(Df,Of)}),Af=I({model:K.optional(),thinkingOptionId:q.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),jf=I({byHarness:z(Df,Af)}),Mf=k().min(1).max(1024),Nf=I({idleRelease:Tf.optional(),favorites:z(Df,P(Mf).max(2048)).default({}),newThread:kf.optional(),delegation:jf.optional()});I({scope:Ef,revision:j().int().nonnegative(),values:Nf}),I({scope:Ef.default(`external`)});let Pf=R(`kind`,[I({kind:V(`idleRelease`),value:Tf}),I({kind:V(`favorite`),harnessId:U,modelId:Mf,enabled:N()}),I({kind:V(`favorites`),harnessId:U,modelIds:P(Mf).max(2048)}),I({kind:V(`newThread`),lastHarness:U.optional(),harnessId:U.optional(),configuration:Of.optional()}),I({kind:V(`delegation`),harnessId:U,configuration:Af.nullable()})]);I({scope:Ef.default(`external`),operations:P(Pf).min(1).max(256),initializeOnly:N().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`})}),I({version:V(1),revision:j().int().nonnegative(),scopes:z(Ef,Nf)});let Ff=j().finite().nonnegative(),If=I({input:Ff,output:Ff,cacheRead:Ff.optional(),cacheWrite:Ff.optional(),cacheWrite1h:Ff.optional()}),Lf=k().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);I({path:k(),entries:P(I({key:k(),price:If})),error:k().nullable()}),I({}),I({key:Lf,price:If.nullable(),previousKey:Lf.optional()}),I({model:Lf});let Rf=I({official:N().optional(),canonicalModelId:k().min(1).optional(),provider:k().min(1).max(512),model:k().min(1).max(512),price:If});I({price:If.nullable(),suggestions:P(Rf).max(6).optional()});let zf=[`today`,`7d`,`30d`,`90d`,`all`],X=j().int().min(0).max(2**53-1),Bf=k().regex(/^\d{4}-\d{2}-\d{2}$/u),Vf=k().min(1).max(128),Hf=k().min(1).max(512),Uf=k().min(1).max(4096);I({range:B(zf),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:Vf.optional(),model:Hf.nullable().optional(),project:Uf.nullable().optional(),date:Bf.optional()});let Wf=I({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}),Gf=Wf.shape,Kf=I({harness:Vf,sessionId:k().min(1).max(512),project:Uf.nullable(),title:k().min(1).max(200).optional(),models:P(Hf).max(16),firstAtMs:X,lastAtMs:X,...Gf});I({range:B(zf),from:Bf.nullable(),to:Bf,filters:I({harness:Vf.nullable(),model:Hf.nullable(),unknownModel:N(),project:Uf.nullable(),unknownProject:N(),date:Bf.nullable()}),reading:I({complete:N(),sources:X,read:X}),failures:P(I({harness:Vf,message:k().max(2048)})).max(256),options:I({harnesses:P(Vf).max(256),models:P(Hf.nullable()).max(4096),projects:P(Uf.nullable()).max(4096)}),modelLabels:P(I({harness:Vf,model:Hf,label:Hf})).max(4096).optional(),credits:P(I({harness:Vf,model:Hf.nullable(),credits:j().finite().min(0),reportedRequests:X,requests:X})).max(4096).optional(),totals:Wf,daily:P(I({date:Bf,harness:Vf,...Gf})).max(2e5),hourly:P(I({weekday:j().int().min(0).max(6),hour:j().int().min(0).max(23),...Gf})).max(168),byHarness:P(I({harness:Vf,...Gf})).max(256),byModel:P(I({model:Hf.nullable(),...Gf,harnessPricedRequests:X})).max(4096),byProject:P(I({project:Uf.nullable(),...Gf})).max(4096),sessions:P(Kf).max(100),recentSessions:P(Kf).max(100).optional()}),F({threadId:W}),F({discarded:N()});let qf=R(`type`,[F({id:k().min(1),type:V(`choice`),prompt:k(),options:P(F({value:k().min(1),label:k(),description:k().optional()})).min(1),multiple:N(),allowOther:N(),optional:N()}),F({id:k().min(1),type:V(`text`),prompt:k(),multiline:N(),secret:V(!1),optional:N(),placeholder:k().optional(),prefill:k().optional()})]),Jf=F({interactionId:k().min(1),turnId:k().min(1),title:k().optional(),questions:P(qf).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});I({threadId:k().min(1)}),F({questions:P(Jf)}),I({threadId:k().min(1),turnId:k().min(1),interactionId:k().min(1),answers:z(k(),P(k())),cancelled:N().default(!1)}),F({accepted:V(!0)});let Yf=`codexhostActiveTurnId`,Xf=/* @__PURE__ */ new Set([Yf,`codexhostTurnChanges`,`codexhostToolOutput`]),Zf=F({path:k(),oldText:k().nullable(),newText:k()});F({sessionId:k().min(1),turn:j().int().nonnegative(),path:k().min(1).optional()}),F({diffs:P(Zf)}),I({}),I({}),F({reference:F({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()}),I({title:k().trim().min(1).max(200),type:B([`info`,`warning`,`danger`]),body:k().trim().min(1).max(16384)}),I({}),I({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.codexhost/update/macos-signing/status.codexhost/update/macos-signing/setup.codexhost/update/macos-signing/remove`.split(`.`));let Qf=B([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),$f=B([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);I({threadId:k(),title:k(),harnessId:k(),state:Qf,reason:$f,inactiveMs:j().nonnegative()}),I({threadId:W,turnId:_l});let ep=F({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:Pl.optional(),balance:Fl.optional()}).strict();function tp(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 np=tp(ep),rp={harnessId:U,harnessName:k().trim().min(1).max(128)},ip=F(rp).strict();F({}).strict(),F({sources:P(ip).max(128)}).strict(),F({harnessId:U,refresh:N().optional()}).strict(),F({...rp,account:np.nullable(),accounts:P(np).max(8).optional()}).strict(),F({refresh:N().optional()}).strict(),F({accounts:P(tp(ep.extend(rp))).max(128)}).strict(),F({harnessId:eu,model:K.optional(),thinkingOptionId:q.optional(),permissionModeId:yl.optional(),prewarm:V(!0).optional()}).strict();let ap=k().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);F({harnessId:eu}).strict().extend({path:ap.nullable()}),F({path:ap.nullable(),restartRequired:N()}).strict(),F({harnessId:U,action:B([`check`,`update`,`install`]),confirmedVersion:k().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let op=F({currentVersion:k().min(1).max(128),latestVersion:k().min(1).max(128),updateAvailable:N(),canUpdate:N(),latestVerifiedVersion:k().min(1).max(128).optional(),confirmationRequired:V(!0).optional(),versionKind:B([`cli`,`application`]).optional(),manualUpdateUrl:Xs().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:hl.optional(),latestVersionKind:B([`unknown`,`tracking-branch`]).optional()}).strict();F({taskId:k().uuid()}).strict(),R(`status`,[F({taskId:k().uuid(),status:V(`running`)}).strict(),F({taskId:k().uuid(),status:V(`succeeded`),result:op}).strict(),F({taskId:k().uuid(),status:V(`failed`),error:F({code:j().int(),message:k().min(1).max(2048)}).strict()}).strict()]);let sp=k().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),cp=k().trim().min(1),lp=B([`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`]),up=F({accountId:sp,label:cp.max(256),email:k().email().max(320).optional(),planType:lp.optional()}).strict(),dp=B([`ready`,`unavailable`]);F({version:V(2),currentAccountId:sp.nullable(),phase:dp,revision:j().int().nonnegative(),instanceId:cp.max(1024).optional(),accounts:P(up).max(1)}).strict(),F({accountId:sp,refresh:N().optional()}).strict(),F({accountId:sp,usage:Ol.nullable(),accountCredits:Pl.optional(),freshness:B([`live`,`cached`]),observedAt:k().datetime().nullable()}).strict();let fp=1e3,pp=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),mp=pp.max(1024),hp=F({nativeSessionId:mp,title:pp.max(4096).nullable(),updatedAt:j().int().nonnegative().max(864e13),cwd:pp.max(16384),running:N().nullable()}).strict();F({}).strict(),F({harnesses:P(F({harnessId:eu,name:pp.max(128)}).strict()).max(128)}).strict(),F({harnessId:eu,query:k().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:j().int().nonnegative().safe().optional(),limit:j().int().min(1).max(fp).optional()}).strict(),F({candidates:P(hp).max(fp),total:j().int().nonnegative().safe()}).strict(),F({harnessId:eu,nativeSessionId:mp}).strict(),F({threadId:pp.max(1024).pipe(W)}).strict();let gp=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),_p=mp,vp=hp;F({}).strict(),F({candidates:P(vp).max(1e3)}).strict(),F({nativeSessionId:_p}).strict(),F({threadId:gp.max(1024).pipe(W)}).strict(),F({threadId:W,lastTurnId:_l}).strict(),F({threadId:W}).strict();let yp=k().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();F({commands:P(F({id:yp,invocation:k().min(1).max(128),label:k().trim().min(1).max(128),description:k().trim().min(1).max(512).optional(),localizations:ml.optional(),argumentMode:B([`none`,`text`]),kind:B([`command`,`skill`]).optional()}).strict()),warnings:P(k().min(1)).optional(),source:B([`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)}),F({harnessId:U,cwd:k().min(1).optional()}).strict(),F({threadId:W}).strict(),F({threadId:W,commandId:yp,turnId:_l.optional(),arguments:ul.optional()}).strict(),F({accepted:V(!0),turnId:_l.optional()}).strict();let bp=V(`2.0`).optional(),Z=bc().optional(),xp=k().min(1),Sp=L([k(),j().int()]),Cp=F({code:j().int(),message:k(),data:H.optional()}).catchall(H).superRefine(al([`data`]));L([F({jsonrpc:bp,id:Sp,method:xp,params:H.optional(),result:Z,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`params`,`result`,`error`])),F({jsonrpc:bp,id:Z,method:xp,params:H.optional(),result:Z,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`id`,`params`,`result`,`error`])),F({jsonrpc:bp,id:Sp,method:Z,params:Z,result:H,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`method`,`params`,`error`])),F({jsonrpc:bp,id:Sp,method:Z,params:Z,result:Z,error:Cp}).catchall(H).superRefine(al([`jsonrpc`,`method`,`params`,`result`]))]);let wp=k().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});I({harnessId:U,nativeSessionId:wp,locator:H.optional(),formatVersion:V(1)}).superRefine(al([`locator`])),I({harnessId:U,nativeSessionId:wp,nativeTurnKey:wp,formatVersion:V(1)}),I({harnessId:U,nativeSessionId:wp,checkpointId:wp,locator:H.optional(),formatVersion:V(1)}).superRefine(al([`locator`]));let Tp=k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Ep=B([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Dp=B([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),Op=I({completed:j().int().nonnegative(),total:j().int().positive()}).refine(e=>e.completed<=e.total,{path:[`completed`],message:`completed must not exceed total`}),kp=I({version:Tp,installation:Ep,phase:Dp,updatedAt:j().int().nonnegative(),downloadedBytes:j().int().nonnegative().optional(),totalBytes:j().int().positive().optional(),npmDownload:Op.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`})});I({});let Ap=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`),jp=B([`idle`,`downloading`,`ready`,`failed`]),Mp=I({downloadedBytes:j().int().nonnegative(),totalBytes:j().int().positive()}).refine(e=>e.downloadedBytes<=e.totalBytes,{path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`});F({currentVersion:Tp,installation:Ep.nullable(),latestVersion:Tp.nullable(),updateAvailable:N(),installationAvailable:N(),releaseNotes:k().min(1).max(2e4).nullable(),releaseNotesUrl:Ap.nullable(),status:kp.nullable(),error:k().min(1).max(500).nullable(),stagedVersion:Tp.nullable().optional(),backgroundPhase:jp.optional(),backgroundDownload:Mp.nullable().optional(),backgroundError:k().min(1).max(500).nullable().optional(),runningTaskCount:j().int().nonnegative().optional()}),I({status:kp}),I({status:kp.nullable()}),I({supported:N(),enabled:N(),certificatePresent:N(),appSignedWithLocalCert:N(),appPath:k().min(1).nullable(),certificateName:k().min(1),certificateSha1:k().regex(/^[0-9A-Fa-f]{40}$/u).nullable()});let Np=I({icon:k().min(1).max(16).optional(),title:k().min(1).max(120),body:k().min(1).max(1200),contributors:P(k().min(1).max(39)).max(30)}),Pp=I({summary:k().min(1).max(600).optional(),themes:P(Np).min(1).max(12)}),Fp=I({version:Tp,publishedAt:il(),url:k().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Pp.nullable(),en:Pp.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});I({manual:N().optional()}),I({announcement:Fp.nullable(),unread:N()}),I({version:Tp}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Ip=B([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);F({runningVersion:k().nullable(),installedVersion:k().nullable(),restartRequired:N(),remote:N(),updateSupported:N(),update:F({phase:Ip,targetVersion:k().nullable(),error:k().nullable()})});let Lp=F({version:k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();F({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:B([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:N().optional(),version:k().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),F({state:B([`installed`,`not-installed`])}).strict();let Q=k().min(1).max(1024),Rp={hostId:Q.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},$={...Rp,threadId:Q},zp=k().min(1).max(8e3),Bp={text:zp,requestId:Q};R(`accepted`,[F({accepted:V(!0),startQueuedItemId:Q.optional()}),F({accepted:V(!1),code:B([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:k()})]),R(`available`,[F({available:V(!1)}),F({available:V(!0),items:P(F({id:Q,clientUserMessageId:Q,preview:k().max(801)})).max(100)})]);let Vp=R(`kind`,[I({kind:V(`hosts`)}),I({kind:V(`create`),...Rp,cwd:k().min(1).max(8192),epoch:Q}),I({kind:V(`projectHarnesses`),...Rp,epoch:Q}),I({kind:V(`inspectHarness`),...Rp,epoch:Q,cwd:k().min(1).max(8192),harnessId:Q}),I({kind:V(`startSelected`),...Rp,epoch:Q,cwd:k().min(1).max(8192),harnessId:Q,model:k().min(1).max(4096),serviceTier:B([`priority`,`ultrafast`]).optional(),reasoningEffort:Q.optional()}),I({kind:V(`status`),...$}),I({kind:V(`list`),...Rp,cursor:k().nullable(),archived:N(),includeLoaded:V(!0).optional()}),I({kind:V(`read`),...$,page:I({cursor:k().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:B([`asc`,`desc`]).optional(),limit:j().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),I({kind:V(`usage`),...$,epoch:Q}),I({kind:V(`configure`),...$,epoch:Q,modelId:Q.optional(),serviceTier:Rl.optional(),thinkingOptionId:Q.optional(),permissionModeId:Q.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),I({kind:V(`prompt`),...$,epoch:Q,text:zp,requestId:Q.optional()}),I({kind:V(`queue`),...$,epoch:Q}),I({kind:V(`delivery`),...$,epoch:Q,action:R(`kind`,[I({kind:V(`enqueue`),...Bp}),I({kind:V(`steer`),...Bp,turnId:Q}),I({kind:V(`remove`),itemId:Q}),I({kind:V(`start`),itemId:Q,onlyIfHead:V(!0).optional()}),I({kind:V(`sendNow`),itemId:Q})])}),I({kind:V(`interrupt`),...$,epoch:Q,turnId:Q}),I({kind:V(`rename`),...$,epoch:Q,name:k().min(1).max(512)}),I({kind:V(`archive`),...$,epoch:Q,archived:N()}),I({kind:V(`respond`),...$,epoch:Q,requestId:L([Q,j().int()]),result:z(k(),vc())})]),Hp=k().min(1).max(1024),Up=F({hostId:Hp,displayName:k().min(1).max(1024),source:B([`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:N(),connectionAnalyticsId:k().max(1024).optional()}),Wp=I({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()});R(`action`,[I({action:V(`session`),operation:Vp}),I({action:V(`list`)}),I({action:V(`catalog`)}),I({action:V(`read-thread`),hostId:Hp.refine(e=>e!==`local`),input:$d}),I({action:V(`save`),draft:Wp,previous:Up.nullable()}),I({action:V(`remove`),previous:Up}),I({action:V(`connect`),hostId:Hp,enabled:N()}),I({action:V(`state`),hostId:Hp}),I({action:V(`runtime`),hostId:Hp}),I({action:V(`update`),hostId:Hp.refine(e=>e!==`local`),version:Lp.shape.version})]),L([I({result:H}),I({error:I({code:j().int(),message:k()})})]),I({prompt:k().trim().min(1).max(2e3),cwd:k().max(4096).nullable()}),k().trim().min(1).max(60).nullable();let Gp=k().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),Kp=L([k(),F({en:k()}).catchall(k())]),qp=F({title:Kp.optional(),description:Kp.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()});F({extensions:P(F({id:Gp,name:k().min(1).max(214),version:k().min(1).max(128),format:V(`dsh`),supportedTargets:Oc([V(`web`)]),enabledTargets:P(V(`web`)).max(1),source:k().min(1).max(4096),projectUrl:k().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:k(),meta:qp.optional(),loadError:k().optional()})),loadedIds:P(Gp),safeMode:N(),storeError:k().optional()});let Jp=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}/`);F({spec:k().trim().min(1).max(4096),registry:Jp.optional()}).strict(),F({id:Gp,enabled:N()}).strict(),F({id:Gp}).strict(),V(1);function Yp(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];
|
|
113
|
+
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)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function wo(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;wo(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}let To=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Eo=[`oneOf`,`anyOf`];function Do(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Oo(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!To.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??Do(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ae(n,r,e.length===1?e[0]:Oo(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=Do(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function ko(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of To)if(t in e)return;let n=t.filter(e=>Eo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Oo(t);else{let e=n[0],i=Eo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Oo([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,yo(e,r))}function Ao(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)):yo(i,s),yo(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??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())wo(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])ko(e)}}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)}yo(i,n.defId?n.schema: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??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ae(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),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:Mo(t,`input`,e.processors),output:Mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function T(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 T(r.element,n);if(r.type===`set`)return T(r.valueType,n);if(r.type===`lazy`)return T(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`||r.type===`catch`)return T(r.innerType,n);if(r.type===`intersection`)return T(r.left,n)||T(r.right,n);if(r.type===`record`||r.type===`map`)return T(r.keyType,n)||T(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:T(r.in,n)||T(r.out,n);if(r.type===`object`){for(let e in r.shape)if(T(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(T(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(T(e,n))return!0;return!!(r.rest&&T(r.rest,n))}return!1}let jo=(e,t={})=>n=>{let r=bo({...n,processors:t});return w(e,r),Co(r,e),Ao(r,e)},Mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=bo({...i??{},target:a,io:t,processors:n});return w(e,o),Co(o,e),Ao(o,e)},No=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Po=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Fo=(e,t)=>{No(e,`minimum`,t),Po(e,`maximum`,t)},Io=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Lo=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Ro=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},zo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Bo=(e,t)=>No(e,`minimum`,t.minimum),Vo=(e,t)=>Po(e,`maximum`,t.maximum),Ho=e=>(t,n)=>{zo(t,n.format);let[r,i]=e[n.format];No(t,`minimum`,r),Po(t,`maximum`,i)},Uo={greater_than:(e,t)=>No(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>Po(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Io(e,t.value),number_format:Ho(Ye),bigint_format:Ho(Xe),min_length:Bo,max_length:Vo,length_equals:(e,t)=>Fo(e,t.length),min_size:Bo,max_size:Vo,size_equals:(e,t)=>Fo(e,t.size),string_format:(e,t)=>{zo(e,t.format),t.pattern&&Lo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Ro(e,t.mime)};function E(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Uo[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&No(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&No(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&Po(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&Po(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Io(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Ro(t,i.mime);for(let e of i.patterns??[])Lo(t,e);return t}let Wo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Go=/* @__PURE__ */ new Map([[Wr,On],[Kr,kn]]),Ko=e=>Go.get(e)??e,qo=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=E(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Wo[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Ko);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}))])}},Jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=E(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):xo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Yo=(e,t,n,r)=>{n.type=`boolean`},Xo=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Zo=(e,t,n,r)=>{n.not={}},Qo=(e,t,n,r)=>{let i=e._zod.def,a=be(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},$o=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(xo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(xo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);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}},es=(e,t,n,r)=>{xo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},ts=(e,t,n,r)=>{xo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ns=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=E(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=w(a.element,t,{...r,path:[...r.path,`items`]})};function rs(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?rs(t.out):t.type===`catch`?rs(t.innerType):e._zod.optin}let is=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&xo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ae(i.properties,e,w(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?rs(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=w(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},as=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>w(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},os=(e,t,n,r)=>{let i=e._zod.def,a=w(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=w(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},ss=(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)=>w(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?w(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?rs(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=E(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function cs(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=cs(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>cs(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Bn:zn).source)),p}let ls=/* @__PURE__ */ new WeakMap;function us(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of ls.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=cs(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}let ds=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=E(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=w(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ae(i.patternProperties,Ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=w(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=ls.get(t);n||(n=[],ls.set(t,n),t.deferred.push(()=>us(t))),n.push(e)}i.additionalProperties=w(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&rs(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},fs=(e,t,n,r)=>{let i=e._zod.def,a=w(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`}]},ps=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ms=Symbol();function hs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(xo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),ms):JSON.parse(o)}let gs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=hs(i.defaultValue,e,t,n,r);o!==ms&&(n.default=o)},_s=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=hs(i.defaultValue,e,t,n,r);o!==ms&&(n._prefault=o)},vs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{xo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},ys=(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;w(o,t,r);let s=t.seen.get(e);s.ref=o},bs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},xs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ss=(e,t,n,r)=>{let i=e._zod.innerType;w(i,t,r);let a=t.seen.get(e);a.ref=i},Cs=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function ws(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}let D=/*@__PURE__*/ y(`ZodError`,(e,t)=>{Ht.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Cs.has(n)||(Cs.add(n),ws(n,`format`,e=>t=>Gt(e,t)),ws(n,`flatten`,e=>t=>Wt(e,t)),ws(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),ws(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Se,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Ts=/* @__PURE__ */ qt(D),Es=/* @__PURE__ */ Jt(D),Ds=/* @__PURE__ */ Yt(D),Os=/* @__PURE__ */ Zt(D),ks=/* @__PURE__ */ rn(D),As=/* @__PURE__ */ an(D),js=/* @__PURE__ */ on(D),Ms=/* @__PURE__ */ sn(D),Ns=/* @__PURE__ */ cn(D),Ps=/* @__PURE__ */ ln(D),Fs=/* @__PURE__ */ un(D),Is=/* @__PURE__ */ dn(D);function Ls(){b.localeError||Ft(ca())}function Rs(){b.memoizer||Ft({memoizer:aa()})}let O=/*@__PURE__*/ y(`ZodType`,(e,t)=>(Ls(),S.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(h(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 Ke(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(nl(e,t))},superRefine(e,t){return this.check(rl(e,t))},overwrite(e){return this.check(/* @__PURE__ */ so(e))},optional(){return Fc(this)},exactOptional(){return Lc(this)},nullable(){return zc(this)},nullish(){return Fc(zc(this))},nonoptional(e){return Gc(this,e)},array(){return P(this)},or(e){return L([this,e])},and(e){return Ec(this,e)},transform(e){return Yc(this,Nc(e))},default(e){return Vc(this,e)},prefault(e){return Uc(this,e)},catch(e){return qc(this,e)},pipe(e){return Yc(this,e)},readonly(){return Zc(this)},describe(e){let t=this.clone();return fa.add(t,{description:e}),t},meta(...e){if(e.length===0)return fa.get(this);let t=this.clone();return fa.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return yt(this,`~standard`,{...fr(this),jsonSchema:{input:Mo(this,`input`),output:Mo(this,`output`)}})},set"~standard"(e){vt(this,`~standard`,e)},parse:function e(t,n){return Ts(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Es(this,t,n,{callee:e})},safeParse(e,t){return Ds(this,e,t)},async safeParseAsync(e,t){return Os(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){vt(this,`spa`,e)},validate(e,t){return en(this,e,t)},validateAsync(e,t){return nn(this,e,t)},encode:function e(t,n){return ks(this,t,n,{callee:e})},decode:function e(t,n){return As(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await js(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Ms(this,t,n,{callee:e})},safeEncode(e,t){return Ns(this,e,t)},safeDecode(e,t){return Ps(this,e,t)},async safeEncodeAsync(e,t){return Fs(this,e,t)},async safeDecodeAsync(e,t){return Is(this,e,t)},toJSONSchema(e){return jo(this,{})(e)},get description(){return fa.get(this)?.description},get _def(){return this._zod.def}}),zs=/*@__PURE__*/ y(`_ZodString`,(e,t)=>{pr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r)},/*@__PURE__*/ bt({format:e=>E(e).format??null,minLength:e=>E(e).minimum??null,maxLength:e=>E(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ to(...e))},includes(...e){return this.check(/* @__PURE__ */ io(...e))},startsWith(...e){return this.check(/* @__PURE__ */ ao(...e))},endsWith(...e){return this.check(/* @__PURE__ */ oo(...e))},min(...e){return this.check(/* @__PURE__ */ $a(...e))},max(...e){return this.check(/* @__PURE__ */ Qa(...e))},length(...e){return this.check(/* @__PURE__ */ eo(...e))},nonempty(...e){return this.check(/* @__PURE__ */ $a(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ no(e))},uppercase(e){return this.check(/* @__PURE__ */ ro(e))},trim(){return this.check(/* @__PURE__ */ lo())},normalize(...e){return this.check(/* @__PURE__ */ co(...e))},toLowerCase(){return this.check(/* @__PURE__ */ uo())},toUpperCase(){return this.check(/* @__PURE__ */ fo())},slugify(){return this.check(/* @__PURE__ */ po())}})),Bs=/*@__PURE__*/ y(`ZodString`,(e,t)=>{pr.init(e,t),zs.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ha(Gs,e))},url(e){return this.check(/* @__PURE__ */ xa(Ys,e))},jwt(e){return this.check(/* @__PURE__ */ Ia(dc,e))},emoji(e){return this.check(/* @__PURE__ */ Sa(Zs,e))},guid(e){return this.check(/* @__PURE__ */ ga(Ks,e))},uuid(e){return this.check(/* @__PURE__ */ _a(qs,e))},uuidv4(e){return this.check(/* @__PURE__ */ va(qs,e))},uuidv6(e){return this.check(/* @__PURE__ */ ya(qs,e))},uuidv7(e){return this.check(/* @__PURE__ */ ba(qs,e))},nanoid(e){return this.check(/* @__PURE__ */ Ca(Qs,e))},cuid(e){return this.check(/* @__PURE__ */ wa($s,e))},cuid2(e){return this.check(/* @__PURE__ */ Ta(ec,e))},ulid(e){return this.check(/* @__PURE__ */ Ea(tc,e))},base64(e){return this.check(/* @__PURE__ */ Na(cc,e))},base64url(e){return this.check(/* @__PURE__ */ Pa(lc,e))},xid(e){return this.check(/* @__PURE__ */ Da(nc,e))},ksuid(e){return this.check(/* @__PURE__ */ Oa(rc,e))},ipv4(e){return this.check(/* @__PURE__ */ ka(ic,e))},ipv6(e){return this.check(/* @__PURE__ */ Aa(ac,e))},cidrv4(e){return this.check(/* @__PURE__ */ ja(oc,e))},cidrv6(e){return this.check(/* @__PURE__ */ Ma(sc,e))},e164(e){return this.check(/* @__PURE__ */ Fa(uc,e))},datetime(e){return this.check(/* @__PURE__ */ La(Vs,e))},date(e){return this.check(/* @__PURE__ */ Ra(Hs,e))},time(e){return this.check(/* @__PURE__ */ za(Us,e))},duration(e){return this.check(/* @__PURE__ */ Ba(Ws,e))}});function k(e){return/* @__PURE__ */ ma(Bs,e)}let A=/*@__PURE__*/ y(`ZodStringFormat`,(e,t)=>{C.init(e,t),zs.init(e,t)}),Vs=/*@__PURE__*/ y(`ZodISODateTime`,(e,t)=>{Mr.init(e,t),A.init(e,t)}),Hs=/*@__PURE__*/ y(`ZodISODate`,(e,t)=>{Nr.init(e,t),A.init(e,t)}),Us=/*@__PURE__*/ y(`ZodISOTime`,(e,t)=>{Pr.init(e,t),A.init(e,t)}),Ws=/*@__PURE__*/ y(`ZodISODuration`,(e,t)=>{Fr.init(e,t),A.init(e,t)}),Gs=/*@__PURE__*/ y(`ZodEmail`,(e,t)=>{gr.init(e,t),A.init(e,t)}),Ks=/*@__PURE__*/ y(`ZodGUID`,(e,t)=>{mr.init(e,t),A.init(e,t)}),qs=/*@__PURE__*/ y(`ZodUUID`,(e,t)=>{hr.init(e,t),A.init(e,t)});function Js(e){return/* @__PURE__ */ _a(qs,e)}let Ys=/*@__PURE__*/ y(`ZodURL`,(e,t)=>{wr.init(e,t),A.init(e,t)});function Xs(e){return/* @__PURE__ */ xa(Ys,e)}let Zs=/*@__PURE__*/ y(`ZodEmoji`,(e,t)=>{Tr.init(e,t),A.init(e,t)}),Qs=/*@__PURE__*/ y(`ZodNanoID`,(e,t)=>{Er.init(e,t),A.init(e,t)}),$s=/*@__PURE__*/ y(`ZodCUID`,(e,t)=>{Dr.init(e,t),A.init(e,t)}),ec=/*@__PURE__*/ y(`ZodCUID2`,(e,t)=>{Or.init(e,t),A.init(e,t)}),tc=/*@__PURE__*/ y(`ZodULID`,(e,t)=>{kr.init(e,t),A.init(e,t)}),nc=/*@__PURE__*/ y(`ZodXID`,(e,t)=>{Ar.init(e,t),A.init(e,t)}),rc=/*@__PURE__*/ y(`ZodKSUID`,(e,t)=>{jr.init(e,t),A.init(e,t)}),ic=/*@__PURE__*/ y(`ZodIPv4`,(e,t)=>{Ir.init(e,t),A.init(e,t)}),ac=/*@__PURE__*/ y(`ZodIPv6`,(e,t)=>{zr.init(e,t),A.init(e,t)}),oc=/*@__PURE__*/ y(`ZodCIDRv4`,(e,t)=>{Br.init(e,t),A.init(e,t)}),sc=/*@__PURE__*/ y(`ZodCIDRv6`,(e,t)=>{Hr.init(e,t),A.init(e,t)}),cc=/*@__PURE__*/ y(`ZodBase64`,(e,t)=>{Gr.init(e,t),A.init(e,t)}),lc=/*@__PURE__*/ y(`ZodBase64URL`,(e,t)=>{Jr.init(e,t),A.init(e,t)}),uc=/*@__PURE__*/ y(`ZodE164`,(e,t)=>{Yr.init(e,t),A.init(e,t)}),dc=/*@__PURE__*/ y(`ZodJWT`,(e,t)=>{Zr.init(e,t),A.init(e,t)}),fc=/*@__PURE__*/ y(`ZodNumber`,(e,t)=>{Qr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jo(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ bt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=E(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=E(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=E(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>E(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},min(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},lt(e,t){return this.check(/* @__PURE__ */ qa(e,t))},lte(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},max(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},int(e){return this.check(M(e))},safe(e){return this.check(M(e))},positive(e){return this.check(/* @__PURE__ */ Ya(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Xa(0,e))},negative(e){return this.check(/* @__PURE__ */ qa(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ Ja(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Za(e,t))},step(e,t){return this.check(/* @__PURE__ */ Za(e,t))},finite(){return this}}));function j(e){return/* @__PURE__ */ Va(fc,e)}let pc=/*@__PURE__*/ y(`ZodNumberFormat`,(e,t)=>{$r.init(e,t),fc.init(e,t)});function M(e){return/* @__PURE__ */ Ha(pc,e)}let mc=/*@__PURE__*/ y(`ZodBoolean`,(e,t)=>{ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r)});function N(e){return/* @__PURE__ */ Ua(mc,e)}let hc=/*@__PURE__*/ y(`ZodNull`,(e,t)=>{ti.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r)});function gc(e){return/* @__PURE__ */ Wa(hc,e)}let _c=/*@__PURE__*/ y(`ZodUnknown`,(e,t)=>{ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function vc(){return/* @__PURE__ */ Ga(_c)}let yc=/*@__PURE__*/ y(`ZodNever`,(e,t)=>{ri.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r)});function bc(e){return/* @__PURE__ */ Ka(yc,e)}let xc=/*@__PURE__*/ y(`ZodArray`,(e,t)=>{Rs(),si.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ $a(e,t))},nonempty(e){return this.check(/* @__PURE__ */ $a(1,e))},max(e,t){return this.check(/* @__PURE__ */ Qa(e,t))},length(e,t){return this.check(/* @__PURE__ */ eo(e,t))},unwrap(){return this.element}});function P(e,t){return/* @__PURE__ */ mo(xc,e,t)}let Sc=/*@__PURE__*/ y(`ZodObject`,(e,t)=>{Rs(),pi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),Et(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(h(this._zod.def,{catchall:e}))},passthrough(){return this.clone(h(this._zod.def,{catchall:vc()}))},loose(){return this.clone(h(this._zod.def,{catchall:vc()}))},strict(){return this.clone(h(this._zod.def,{catchall:bc()}))},strip(){return this.clone(h(this._zod.def,{catchall:void 0}))},extend(e){return et(this,e)},safeExtend(e){return nt(this,e)},merge(e){return rt(this,e)},pick(e){return Ze(this,e)},omit(e){return $e(this,e)},partial(...e){return it(Pc,this,e[0])},exactPartial(...e){return it(Ic,this,e[0],`exactPartial`)},required(...e){return at(Wc,this,e[0])}});function F(e,t){let n={type:`object`,shape:e??{},...g(t)};return new Sc(n)}function I(e,t){return new Sc({type:`object`,shape:e,catchall:bc(),...g(t)})}let Cc=/*@__PURE__*/ y(`ZodUnion`,(e,t)=>{hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.options=t.options});function L(e,t){return new Cc({type:`union`,options:e,...g(t)})}let wc=/*@__PURE__*/ y(`ZodDiscriminatedUnion`,(e,t)=>{Cc.init(e,t),_i.init(e,t)});function R(e,t,n){return new wc({type:`union`,options:t,discriminator:e,...g(n)})}let Tc=/*@__PURE__*/ y(`ZodIntersection`,(e,t)=>{vi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)});function Ec(e,t){return new Tc({type:`intersection`,left:e,right:t})}let Dc=/*@__PURE__*/ y(`ZodTuple`,(e,t)=>{Rs(),xi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ss(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Pc({type:`optional`,innerType:e}))})}});function Oc(e,t,n){let r=t instanceof S;return new Dc({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let kc=/*@__PURE__*/ y(`ZodRecord`,(e,t)=>{Rs(),Ti.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return!t||!t._zod?new kc({type:`record`,keyType:k(),valueType:e,...g(t)}):new kc({type:`record`,keyType:e,valueType:t,...g(n)})}let Ac=/*@__PURE__*/ y(`ZodEnum`,(e,t)=>{Ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];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 Ac({...t,checks:[],...g(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 Ac({...t,checks:[],...g(r),entries:i})}});function B(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ac({type:`enum`,entries:n,...g(t)})}let jc=/*@__PURE__*/ y(`ZodLiteral`,(e,t)=>{Di.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(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 V(e,t){return new jc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let Mc=/*@__PURE__*/ y(`ZodTransform`,(e,t)=>{Rs(),Oi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Pt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(gt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(gt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Nc(e){return new Mc({type:`transform`,transform:e})}let Pc=/*@__PURE__*/ y(`ZodOptional`,(e,t)=>{Ai.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Fc(e){return new Pc({type:`optional`,innerType:e})}let Ic=/*@__PURE__*/ y(`ZodExactOptional`,(e,t)=>{ji.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Lc(e){return new Ic({type:`optional`,innerType:e})}let Rc=/*@__PURE__*/ y(`ZodNullable`,(e,t)=>{Mi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function zc(e){return new Rc({type:`nullable`,innerType:e})}let Bc=/*@__PURE__*/ y(`ZodDefault`,(e,t)=>{Ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Vc(e,t){return new Bc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Hc=/*@__PURE__*/ y(`ZodPrefault`,(e,t)=>{Fi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Uc(e,t){return new Hc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Wc=/*@__PURE__*/ y(`ZodNonOptional`,(e,t)=>{Ii.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ps(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Gc(e,t){return new Wc({type:`nonoptional`,innerType:e,...g(t)})}let Kc=/*@__PURE__*/ y(`ZodCatch`,(e,t)=>{zi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function qc(e,t){return new Kc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Dt(t)})}let Jc=/*@__PURE__*/ y(`ZodPipe`,(e,t)=>{Bi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.in=t.in,e.out=t.out});function Yc(e,t){return new Jc({type:`pipe`,in:e,out:t})}let Xc=/*@__PURE__*/ y(`ZodReadonly`,(e,t)=>{Hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Zc(e){return new Xc({type:`readonly`,innerType:e})}let Qc=/*@__PURE__*/ y(`ZodLazy`,(e,t)=>{Wi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ss(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function $c(e){return new Qc({type:`lazy`,getter:e})}let el=/*@__PURE__*/ y(`ZodCustom`,(e,t)=>{Gi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r)});function tl(e,t){return/* @__PURE__ */ ho(el,e??(()=>!0),t)}function nl(e,t={}){return/* @__PURE__ */ go(el,e,t)}function rl(e,t){return/* @__PURE__ */ _o(e,t)}function il(e){return/* @__PURE__ */ La(Vs,e)}function al(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 ol=L([k(),j(),N(),gc()]);function sl(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 cl=tl(sl,{message:`JSON value must not contain circular references`}),ll=$c(()=>L([ol,P(ll),z(k(),ll)])),H=cl.pipe(ll);cl.pipe(P(ll));let ul=cl.pipe(z(k(),ll)),dl=I({code:k().min(1),message:k().min(1),retryable:N(),diagnostic:k().min(1).optional(),stage:k().min(1).optional(),durationMs:j().int().nonnegative().optional(),stderrTail:k().min(1).optional()}).superRefine(al([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),fl=k().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),pl=e=>k().min(1).max(e).refine(e=>e.trim().length>0),ml=z(fl,F({label:pl(256).optional(),description:pl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),hl=z(fl,pl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),gl=k().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),U=gl.brand(),W=gl.brand(),_l=gl.brand();gl.brand(),gl.brand();let vl=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),yl=vl.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),bl=F({modes:P(F({id:yl,label:vl.max(256),description:vl.max(1024).optional(),dangerous:N().optional(),localizations:ml.optional()}).strict()).min(1).max(32),defaultModeId:yl}).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`]})});F({threadId:W,permissionModeId:yl}).strict();let xl=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`});F({sourceThreadId:W,lastTurnId:_l.optional(),targetHarnessId:U,targetModel:xl.max(1024).optional(),targetThinkingOptionId:xl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).optional()}).strict();let Sl=F({sourceThreadId:W,sourceHarnessId:U,sourceHarnessLabel:xl.max(256).optional(),sourceModel:xl.max(1024).optional(),targetHarnessId:U,targetHarnessLabel:xl.max(256).optional(),targetModel:xl.max(1024).optional(),totalTurns:j().int().min(1),boundaryTurnNumber:j().int().min(1),includedTurnNumbers:P(j().int().min(1)),omittedTurns:j().int().min(0),preview:k().max(32e3),createdAtMs:j().int().nonnegative()}).strict();F({threadId:W,handoff:Sl}).strict();let G=j().int().safe().nonnegative(),Cl=j().finite().nonnegative(),wl=j().finite().min(0).max(100),Tl=F({version:L([V(3),V(4)]).optional(),requestId:k().min(1),turnId:k().min(1).max(1024),outputTokens:G,startedAtMs:G,completedAtMs:G}).strict().refine(e=>e.completedAtMs>e.startedAtMs),El=F({version:L([V(2),V(3),V(4)]).optional(),value:Cl,turnId:k().min(1).max(1024),at:G}).strict();F({outputTimings:P(Tl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:El.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:El.extend({value:G}).optional()}).strict();let Dl=e=>hl.refine(t=>Object.values(t).every(t=>t.length<=e)),Ol=F({composerIndicators:P(F({kind:V(`countdown`),id:k().min(1).max(64),expiresAtUnix:G,label:Dl(256).optional(),tooltip:Dl(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:G.optional(),cachedInputTokens:G.optional(),cacheWriteInputTokens:G.optional(),outputTokens:G.optional(),outputTokensPerSecond:Cl.optional(),sessionOutputTokensPerSecond:Cl.optional(),apiOutputTokensPerSecond:Cl.optional(),reasoningOutputTokens:G.optional(),totalTokens:G.optional(),totalCostUsd:Cl.optional(),totalCredits:Cl.optional(),contextUsagePercent:Cl.optional(),cacheHitRatePercent:wl.optional(),contextWindowTokens:G.optional(),contextUsedTokens:G.optional(),planFiveHourUsedPercent:wl.optional(),planFiveHourResetsAtUnix:G.optional(),planSevenDayUsedPercent:wl.optional(),planSevenDayResetsAtUnix:G.optional(),sessionCacheHitRatePercent:wl.optional(),timeToFirstOutputMs:G.optional(),latestRequestTimeToFirstOutputMs:G.optional(),costSource:B([`publicPrice`,`native`]).optional(),unpricedModels:P(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`]})}),kl=j().finite().min(0).max(100),Al=B([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),jl=F({id:k().min(1).max(256),label:k().min(1).max(256),localizations:ml.optional()}).strict(),Ml=F({product:k().min(1),periodType:Al.optional(),scope:jl.optional(),localizations:ml.optional(),used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),usagePercent:kl,resetsAt:k().min(1).optional()}).strict(),Nl=F({availableCount:j().int().safe().positive(),nextExpiresAt:k().min(1).optional(),expiresAt:P(k().min(1)).min(1).max(32).optional()}).strict(),Pl=F({used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),label:k().min(1).optional(),scope:jl.optional(),localizations:ml.optional(),usedPercent:kl,resetsAt:k().min(1).optional(),periodType:Al,productUsage:P(Ml).min(1).optional(),resetCredits:Nl.optional()}).strict(),Fl=F({amount:j().finite().nonnegative(),currency:k().trim().min(1).max(8),label:k().trim().min(1).max(128).optional()}).strict();F({threadId:W,refresh:V(`exact`).optional()}).strict(),F({threadId:W,usage:Ol.nullable(),accountCredits:Pl.optional(),accountBalance:Fl.optional(),accountCreditsSupported:N().optional()}).strict();let Il=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ll=k().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Rl=B([`priority`,`ultrafast`]),K=F({id:Ll,serviceTier:Rl.optional()}).strict();function zl(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let q=Il.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Bl=Il.max(256),Vl=F({id:q,label:Il.max(256)}).strict(),Hl=F({ref:K,label:Il.max(256),resolvedModelLabel:Bl.optional(),fastModel:K.optional(),supportedThinkingOptionIds:P(q).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function Ul(e,t){if(t)return e?.models.find(e=>zl(e.ref,t)||zl(e.fastModel,t))}let Wl=P(Vl).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)}),Gl=B([`catalog`,`activeModel`]),Kl=F({models:P(Hl),defaultModel:K.optional(),thinkingOptions:Wl,defaultThinkingOptionId:q.optional(),thinkingOptionsScope:Gl.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>zl(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>zl(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!Ul(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),ql=F({fork:N(),forkAcrossCwd:N(),rollbackLastTurn:N()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Jl=B([`live`,`atCreate`]),Yl=F({configuration:F({selectModel:N(),selectThinkingOption:N(),selectPermissionMode:N(),permissionModeScope:Jl.default(`live`)}).strict(),history:ql,subagents:F({observe:N(),readTranscript:N()}).strict().optional(),autonomousTurns:F({observe:N()}).strict().optional(),steer:N().optional(),persistentPlan:N().optional()}).strict();F({effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),availableThinkingOptions:Wl.optional(),effectivePermissionModeId:yl.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 Xl=F({open:V(!0)}).strict();L([F({status:V(`ready`),catalog:Kl,permissionModes:bl.optional(),capabilities:Yl,webUi:Xl.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`]})}),F({status:B([`notInstalled`,`unavailable`,`error`]),error:dl}).strict()]),F({harnessId:U,cwd:Il.max(16384).optional(),refresh:N().optional(),purpose:V(`availability`).optional(),credentialAccess:B([`allow`,`retry`]).optional()}).strict(),F({harnessId:U}).strict(),F({}).strict(),F({threadId:W,model:K}).strict(),F({threadId:W,thinkingOptionId:q}).strict(),F({threadId:W,includeReferenceCapability:N().optional()}).strict(),R(`owner`,[F({owner:V(`codex`),locked:N(),effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),effectivePermissionModeId:yl.optional(),history:ql.optional(),supportsThreadReferences:V(!0).optional(),handoff:Sl.optional()}).strict(),F({owner:V(`external`),harnessId:Il.max(256),transportModelId:Il.max(8192),effectiveModel:K.optional(),resolvedModelLabel:Bl.optional(),effectiveThinkingOptionId:q.optional(),availableThinkingOptions:Wl.optional(),effectivePermissionModeId:yl.optional(),catalog:Kl.optional(),history:ql,usage:Ol.optional(),handoff:Sl.optional(),locked:V(!0)}).strict()]),F({threadIds:P(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 Zl=R(`owner`,[F({threadId:W,owner:V(`codex`)}).strict(),F({threadId:W,owner:V(`external`),harnessId:k().max(256).pipe(U)}).strict()]);F({threads:P(Zl).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)}),F({threadId:W,text:k().optional()}).strict(),F({kind:V(`application`),value:k().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),kt}}).pipe(F({expectedTurnId:_l,clientUserMessageId:k().min(1),delivery:B([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),B([`activeTurn`,`newTurn`]),F({delivery:B([`official`,`activeTurn`,`newTurn`])}).strict();let Ql=k().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),$l=Ql.pipe(U),eu=$l.refine(e=>e!==`codex`,`The official Codex identity is reserved`),tu=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`),nu=Xs().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),ru=F({en:k().max(4096),"zh-CN":k().max(4096).optional()}).strict(),iu=F({commands:P(F({terminal:k().max(256),command:k().max(4096)}).strict()).max(8),before:ru.optional(),after:ru.optional(),downloads:P(F({label:k().max(128),url:nu}).strict()).max(8).optional()}).strict(),au={id:$l,name:k().trim().min(1).max(128),version:k().min(1).max(128),kind:V(`usage`).optional(),iconStyle:F({vector:F({viewBox:k().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:P(F({d:k().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:B([`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:iu.optional(),notice:ru.optional(),launchCommand:V(!0).optional(),links:F({website:nu.optional(),documentation:nu.optional(),installation:nu.optional()}).strict().optional()};F({manifestVersion:V(1),...au,adapterApiVersion:j().int().positive(),entry:tu,icon:tu.optional()}).strict();let ou=k().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),su=F({...au,icon:ou.optional()}).strict();F({}).strict(),F({plugins:P(su.extend({id:eu})).max(128)}).strict(),F({version:V(1),enabled:P($l).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let cu=131072,lu=Ql,uu=B([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),du=B([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),fu=k().trim().min(1).max(128);function pu(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let mu=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),hu=tu.refine(e=>pu(e)!==void 0&&mu(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),gu=k().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Xs({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function _u(e){return I({en:e,"zh-CN":e})}let vu=_u(k().trim().min(1)),yu=P(du).max(du.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),bu=P(uu).max(uu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),xu={key:k().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:vu,description:vu.optional()},Su={...xu,step:j().positive().optional(),default:j().optional()},Cu=I({value:k(),label:vu}),wu=R(`type`,[I({...xu,type:V(`boolean`),default:N().optional()}),I({...xu,type:V(`string`),placeholder:vu.optional(),default:k().optional()}),I({...Su,type:V(`number`),min:j().optional(),max:j().optional()}),I({...Su,type:V(`range`),min:j(),max:j()}),I({...xu,type:V(`select`),options:P(Cu).min(1),default:k().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),Tu=F({manifestVersion:M().positive(),id:lu,name:L([fu,_u(fu)]),version:k().min(1).max(128),desktopApi:M().positive()}).passthrough().extend({manifestVersion:V(1),desktopApi:V(1),description:I({en:k().max(4096),"zh-CN":k().max(4096).optional()}).optional(),author:k().trim().min(1).max(128).optional(),repository:gu.optional(),details:I({en:k().max(16384),"zh-CN":k().max(16384).optional()}).optional(),icon:hu.optional(),screenshots:P(hu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:I({script:tu,style:tu.optional()}).optional(),backend:I({script:tu.refine(mu)}).optional(),slots:bu.default(()=>[]),settingsSchema:P(wu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:yu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),Eu=k().regex(/^[a-f0-9]{64}$/u),Du=I({state:B([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:Eu.optional(),error:k().optional(),conflictWith:lu.optional()});I({controllerPid:M().positive(),targetId:k().nullable(),updatedAt:il(),handledReloadToken:Js().optional(),extensions:z(k(),Du),surfaces:z(k(),Du).optional()});let Ou=B([`official`,`community`]);function ku(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Au=gu.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||ku(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),ju=I({id:lu,version:k().trim().min(1).max(128),name:vu.extend({en:fu,"zh-CN":fu}),description:_u(k().trim().min(1).max(4096)),details:_u(k().trim().min(1).max(16384)).optional(),author:k().trim().min(1).max(128),repository:gu,stars:j().int().min(0).optional(),downloads:j().int().min(0).optional(),categories:yu.optional(),trustTier:Ou.default(`community`),icon:gu.optional(),screenshots:P(gu).max(4).optional(),downloadUrl:Au,sha256:Eu,slots:bu.optional(),publishedAt:k().optional(),updatedAt:k().optional(),minCodexHostVersion:k().optional()});I({schemaVersion:V(1),generatedAt:k(),extensions:P(ju).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Mu=k().trim().min(1).max(128),Nu=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,Pu=lu.refine(e=>!Nu.test(e),`Reserved extension ID`),Fu=B([`desktop`,`web`]),Iu=Eu,Lu=Js(),Ru=tu.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Nu.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),zu=Tu.shape,Bu=(e,t=0)=>I({en:k().trim().min(t).max(e),"zh-CN":k().trim().min(t).max(e)}),Vu=e=>Ru.refine(t=>t.endsWith(e),`Expected a ${e} file`),Hu=Vu(`.mjs`),Uu=Vu(`.css`).optional(),Wu=e=>e.normalize(`NFC`).toLowerCase(),Gu=I({manifestVersion:V(2),id:Pu,name:Bu(128,1),version:k().trim().min(1).max(128),description:Bu(4096),details:Bu(16384).optional(),author:zu.author,repository:zu.repository,icon:zu.icon.refine(e=>e===void 0||Ru.safeParse(e).success),screenshots:zu.screenshots.refine(e=>e===void 0||e.every(e=>Ru.safeParse(e).success)),categories:zu.categories,settingsSchema:zu.settingsSchema,slots:zu.slots.removeDefault().optional(),page:I({apiVersion:V(1),entry:Hu,style:Uu,title:Bu(128,1).optional()}).optional(),widget:I({apiVersion:V(1),entry:Hu,style:Uu}).optional(),desktop:I({apiVersion:V(1),script:Vu(`.js`),style:Uu}).optional(),web:I({apiVersion:V(1),entry:Hu.optional(),style:Uu}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:I({apiVersion:V(1),entry:Hu}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||Wu(e)!==Wu(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Ku({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let qu=Mu,Ju=B([`running`,`waiting`,`idle`,`unknown`]),Yu=I({sourceThreadId:W,createdAtMs:j().int().nonnegative()}),Xu=I({harnessId:U,title:k().optional(),status:Ju,archived:N(),updatedAtMs:j().int().nonnegative().optional()}),Zu=I({revision:M().nonnegative(),parents:z(W,W),handoffs:z(W,Yu).optional(),nodes:z(W,Xu),truncated:N()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,handoffs:t,nodes:n})=>Object.entries(e).every(([e,t])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t))&&Object.entries(t??{}).every(([e,{sourceThreadId:t}])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t)),`Missing Thread tree node`),Qu=k().min(1).max(128);I({});let $u=I({subscriptionId:Qu});I({}),$u.extend({snapshot:Zu});let ed=M().nonnegative(),td=I({revision:ed,enabled:P(Pu).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});I({version:V(1),seeded:P(Pu).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});let nd=F({version:k().trim().min(1).max(128),publishedAt:k().trim().min(1).max(64).optional(),notes:k().trim().min(1).max(8192),url:gu.optional()}),{downloadUrl:rd,...id}=ju.shape,ad=F({...id,id:Pu,format:V(`codexhost`),targets:P(Fu).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:I({page:M().positive().optional(),widget:M().positive().optional(),desktop:M().positive().optional(),web:M().positive().optional(),backend:M().positive().optional()}),downloadUrl:rd.refine(e=>e.startsWith(`https://`),`Expected HTTPS`),featured:N().optional(),featuredOrder:M().nonnegative().optional(),changelog:P(nd).max(20).optional()}).refine(({targets:e,apis:t})=>{let n=Ku({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);F({schemaVersion:V(2),generatedAt:k().min(1),extensions:P(ad).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:gu,fetchedAt:il(),cached:N(),stale:N().optional()});let od={id:Pu},sd={...od,activationId:Lu,digest:Iu},cd={...od,activationId:sd.activationId.optional()},ld=k().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),ud=k().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function dd(e){return k().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let fd=I({type:V(`github`),repository:k().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:ud.optional(),tag:ud.optional(),asset:k().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Ru.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),pd=L([I({type:V(`catalog`),...od}),fd,I({type:V(`zip`),base64:dd(67108864).min(4)}),I({type:V(`zip`),localZipPath:ld}),I({type:V(`localDir`),localDir:ld})]),md=R(`type`,[I({type:V(`catalog`),...od}),fd,I({type:V(`zip`)}),I({type:V(`localDir`)})]),hd=I({...sd,manifest:Gu,installedAt:il(),source:md.optional()}),gd=e=>k().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),_d={desktopConflictWith:Pu.optional()},vd=B([`none`,`inactive`,`starting`,`running`,`failed`]),yd=R(`state`,[hd.extend({state:V(`valid`),enabled:N(),..._d,iconDataUrl:gd(cu).optional(),screenshotDataUrls:P(gd(524288)).max(4).optional(),backendState:vd.optional(),backendError:k().optional()}),I({state:B([`invalid`,`incompatible`]),id:k().min(1),enabled:N(),error:k()})]);I({revision:ed,configuration:td,diagnostics:P(k()),extensions:P(yd)}),I({revision:ed,extensions:P(hd.extend({..._d,settingsRevision:ed})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,catalogIcon:`codexhost/extensions/catalogIcon`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`,threadTree:`codexhost/extensions/threadTree`},bd=Object.freeze(Object.values(J));new Set(bd),I({});let xd={expectedRevision:ed};I({...od,...xd}),hd.extend({replaced:N()}),R(`state`,[I({state:V(`saved`),configuration:td}),I({state:V(`revision-conflict`),revision:ed})]),I({...cd,digest:sd.digest.optional(),path:Ru}),I({mimeType:k().min(1),base64:dd(16777216),digest:sd.digest}),I({mimeType:B([`image/png`,`image/jpeg`,`image/webp`]),base64:dd(cu)}),I({settingsRevision:ed,values:ul}),J.list,J.snapshot,J.catalog,I({forceRefresh:N().optional(),staleWhileRevalidate:N().optional()}),J.catalogIcon,I({...od}),J.install,I({source:pd}),J.update,I({...od,expectedDigest:sd.digest,expectedActivationId:sd.activationId.optional(),source:pd.optional()}),J.enable,J.disable,J.uninstall,I({...od,removeData:N().optional(),expectedDigest:sd.digest.optional()}),I({...od,removed:N()}),J.recover,I({expectedRevision:xd.expectedRevision.optional()}),J.asset,J.settingsGet,I(cd),J.settingsSet,I({...cd,expectedSettingsRevision:ed,values:ul}),J.backendInvoke,I({...cd,method:qu,params:H.optional()}),I({result:H}),J.threadTree,F({threadId:W}).strict(),F({confirmed:N()}).strict();let Sd=[`codex-desktop`,`web`,`web-desktop-shell`,`web-mobile`,`ssh-remote`,`cli`],Cd=[`darwin`,`win32`,`linux`],wd=[`arm64`,`x64`,`ia32`,`arm`],Td=[`zh`,`en`,`ja`,`ko`,`de`,`fr`,`es`,`pt`,`ru`,`other`],Ed=[`codex`,`claude-code`,`antigravity`,`pi`,`opencode`,`cursor-cli`,`deepseek-harness`,`grok`,`omp`,`qwen-code`,`kiro-cli`,`codebuddy`,`workbuddy`,`devin`,`hermes`,`qoder`,`qoder-cn`,`kimi-code`,`zcode`,`copilot`,`custom`],Dd=[`official-relay`,`self-hosted-relay`,`tailscale-serve`,`tailscale-funnel`,`tailscale-ip`,`lan`,`custom-proxy`,`remote-peer`],Od=k().min(1).max(40).regex(/^[0-9A-Za-z._+-]+$/u),kd=B(Sd),Ad=B(Td),jd=B(Ed),Md=B(Dd);new Set(Ed),new Set(Td),F({enabled:N(),forcedOffByEnv:N()}).strict(),F({enabled:N()}).strict(),F({surfaces:P(kd).max(12).optional(),harnesses:P(jd).max(32).optional(),remoteAccess:P(Md).max(12).optional()}).strict(),F({dailyActive:V(!0).optional(),weeklyActive:V(!0).optional(),monthlyActive:V(!0).optional(),newInstall:V(!0).optional(),retainedD1:V(!0).optional(),retainedD7:V(!0).optional(),remoteAny:V(!0).optional(),appVersion:Od.optional(),codexDesktopVersion:Od.optional(),os:B(Cd).optional(),arch:B(wd).optional(),uiLanguage:Ad.optional(),surfaces:P(kd).min(1).max(12).optional(),harnesses:P(jd).min(1).max(32).optional(),remoteAccess:P(Md).min(1).max(12).optional()}).strict().refine(e=>Object.keys(e).length>0,{message:`Telemetry heartbeat must contain at least one countable field`});let Nd=4e3,Pd={threadId:W};R(`action`,[I({...Pd,action:B([`get`,`pause`,`resume`,`clear`])}),I({...Pd,action:B([`create`,`edit`]),objective:k().trim().min(1).refine(e=>Array.from(e).length<=Nd,`A goal objective can have up to ${Nd} characters.`)})]),F({goal:F({threadId:W,objective:k(),status:B([`active`,`paused`,`blocked`,`usageLimited`,`budgetLimited`,`complete`]),tokenBudget:M().positive().nullable().default(null),tokensUsed:M().nonnegative(),timeUsedSeconds:M().nonnegative()}).nullable()});let Fd=k().trim().min(1),Id=k().min(1),Ld=F({icon:k().nullable(),color:k().nullable()}),Rd=Ld.nullable(),zd={create:{method:`codexhost/thread/sections/create`,params:F({name:Fd}).strict()},update:{method:`codexhost/thread/sections/update`,params:F({sectionId:Id,name:Fd,appearance:Ld.strict().nullable().optional()}).strict()},delete:{method:`codexhost/thread/sections/delete`,params:F({sectionId:Id}).strict()}};R(`status`,[F({status:V(`unknown`)}),F({status:V(`confirmed`),sectionId:Id,section:F({id:Id,name:k().min(1),appearance:Rd}).nullable(),syncPending:N()})]),[zd.create.method,zd.update.method,zd.delete.method,...bd],F({threadSectionsV1:V(!0).optional(),complete:V(!1).optional(),sections:P(F({id:k().min(1),name:k().min(1),appearance:Rd.optional(),threads:P(ul)}))}),F({threadId:k().min(1).max(1024),sectionId:k().min(1).max(1024).nullable(),beforeThreadId:k().min(1).max(1024).nullable().optional(),expectedSourceSectionId:k().min(1).max(1024).optional()}).refine(e=>e.expectedSourceSectionId===void 0||e.sectionId===null),F({threadIds:P(k().min(1))}).strict(),F({threadId:k().min(1).max(1024),pinned:N()}).strict(),F({}).strict(),F({parents:z(k().min(1),k().min(1))}).strict(),F({prompt:k().max(16384).optional()}).strict(),F({projects:P(F({id:k(),name:k(),rootPaths:P(k()),createdAt:j().int().optional()})),nativeProjects:V(!0).optional(),assignments:z(k(),k()),projectless:P(k()),pinned:P(k()),sectionProjects:z(k(),P(k())).optional(),pinnedProjects:P(k()).optional()});let Bd=z(k(),vc()),Vd=F({epoch:k().uuid(),sequence:j().int().nonnegative()});R(`type`,[F({type:V(`projects-changed`),cursor:Vd}),F({type:V(`skills-changed`),cursor:Vd,cwd:k().optional()}),F({type:V(`harness-inspection-changed`),cursor:Vd,harnessId:k().min(1)}),F({type:V(`display-settings-changed`),cursor:Vd}),F({type:V(`sections-changed`),cursor:Vd}),F({type:V(`preferences-changed`),cursor:Vd,revision:j().int().nonnegative()}),F({type:V(`extensions-changed`),cursor:Vd,revision:ed}),F({type:V(`hello`),version:V(1),cursor:Vd,reset:N()}),F({type:V(`changed`),cursor:Vd,threadId:k().min(1),method:k().min(1)})]);let Hd=R(`type`,[F({type:V(`text`),id:k(),prompt:k(),secret:N().optional(),optional:N().optional()}),F({type:V(`choice`),id:k(),prompt:k(),multiple:N(),allowOther:N(),optional:N().optional(),options:P(F({value:k(),label:k(),description:k().optional()}))})]),Ud=R(`type`,[F({type:V(`approval`),title:k(),description:k().optional(),subject:vc().optional(),actions:P(F({id:k(),label:k(),effect:k()}))}),F({type:V(`question`),title:k().optional(),questions:P(Hd)})]),Wd=F({requestId:L([k(),j().int()]),threadId:k(),kind:B([`approval`,`question`]),interaction:Ud,request:Bd}),Gd=F({id:k().min(1),clientUserMessageId:k().min(1),input:P(Bd),presentationInput:P(Bd).nullable().optional()}).passthrough();F({fields:P(F({path:P(L([k(),j().int().nonnegative()])),originalLength:j().int().nonnegative()}))});let Kd=F({id:k().min(1),status:k().min(1),codexhostTurnOutcome:F({status:V(`unknown`),reason:k()}).optional(),items:P(F({id:k().min(1),type:k().min(1)}).passthrough()),codexhostFileOperations:P(F({beforeItemId:k().nullable(),item:F({id:k().min(1),type:k().min(1)}).passthrough()})).optional(),error:F({message:k().optional()}).passthrough().nullable().optional(),fingerprint:k().min(1).optional(),unchanged:V(!0).optional()}).passthrough(),qd=F({id:k().min(1).max(512),fingerprint:k().min(1).max(128)});F({threadId:k().min(1),knownTurns:P(qd).max(64).optional(),truncateToolOutput:N().optional()});let Jd=F({harnessId:k().min(1),nativeSessionId:k().min(1)});F({cursor:Vd,activeTurnId:k().min(1).nullable().optional(),command:F({name:k().min(1),turn:Kd,subsequentTurnId:k().min(1).optional()}).optional(),thread:F({id:k().min(1),cwd:k(),modelProvider:k().min(1),createdAt:j(),updatedAt:j(),recencyAt:j().nullable().optional(),status:F({type:k()}).passthrough(),name:k().nullable().optional(),preview:k().optional(),codexhostImportSource:Jd.optional(),turns:P(Kd).length(0)}).passthrough(),turnsPage:F({data:P(Kd).max(5),nextCursor:k().nullable()}),configuration:F({native:F({model:k().min(1).max(1024).optional(),reasoningEffort:k().min(1).max(128).optional()}).optional(),effectiveModel:K.optional(),effectiveThinkingOptionId:q.optional(),effectivePermissionModeId:yl.optional()}),queue:F({items:P(Gd),pausedReason:B([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:P(Wd),handoff:Sl.optional()}),F({version:V(1),owner:V(`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(),capabilities:F({peerDelegation:V(1).optional(),threadReferenceContext:V(1).optional()}).optional()}),F({epoch:k().uuid(),threadId:k().min(1),requestId:L([k(),j().int()]),result:Bd}),F({includeArchived:N().optional(),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional(),scope:L([F({cwd:k().min(1).max(4096),excludeCwds:P(k().min(1).max(4096)).max(1024)}).strict(),F({projectId:k().min(1).max(1024),legacyThreadIds:P(k().min(1).max(1024)).max(1024),rootPaths:P(k().min(1).max(4096)).max(1024).optional()}).strict()]).optional()}).strict(),F({threads:P(ul),ownership:P(Zl),archivedThreadIds:P(W),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional()}).strict(),su.pick({id:!0,name:!0,icon:!0,iconStyle:!0});let Yd=I({threadId:k().max(1024),title:k().max(240),project:k().max(240),harness:I({id:k().min(1).max(128),name:k().min(1).max(128)}).optional(),state:B([`idle`,`running`,`waiting`,`completed`,`failed`]),updatedAt:j().nonnegative()});I({epoch:k().max(128),revision:M().nonnegative(),running:M().nonnegative(),waiting:M().nonnegative(),sessions:P(Yd).max(32).default([]),notifications:P(I({threadId:k().max(1024),key:k().max(4096),kind:B([`completed`,`failed`,`approval`,`question`]),revision:M().nonnegative()})).max(256)});let Xd=k().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);F({available:N()}).strict(),F({path:k().min(1),mimeType:Xd}).strict();let Zd=B([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);R(`ok`,[F({ok:V(!0),text:k()}).strict(),F({ok:V(!1),error:F({code:Zd}).strict()}).strict()]),F({threadId:W.optional(),cwd:k().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Qd=F({name:k().min(1).regex(/^[^\s[\]]+$/u),description:k().optional(),path:k().min(1),scope:B([`project`,`global`]),source:k().min(1)}).strict();F({revision:j().int().nonnegative(),complete:N(),skills:P(Qd),warnings:P(k()).optional()}).strict(),F({cwd:k().min(1).optional()}).strict();let $d=F({kind:B([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:k().min(1)}).strict(),ef=R(`status`,[F({status:V(`not-installed`)}),F({status:V(`not-running`)}),F({status:V(`not-logged-in`)}),F({status:V(`https-disabled`)}),F({status:V(`not-serving`),command:k()}),F({status:V(`occupied`),target:k()}),F({status:V(`serving`),url:k(),funnel:N()}),F({status:V(`error`),message:k()})]);F({state:ef,error:k().optional()}).strict();let tf=R(`status`,[F({status:V(`on`)}),F({status:V(`off`)}),F({status:V(`invalid`),reason:k()})]),nf=F({lan:N(),autostart:tf}).strict(),rf=F({expiresAt:k().optional(),issuing:N(),failure:F({detail:k().optional(),retryAt:k(),paused:N()}).optional()}),af=R(`status`,[F({status:V(`off`),reason:B([`invite`,`name-taken`,`banned`]).optional()}),F({status:V(`connecting`),reason:B([`full`,`unreachable`]).optional()}),F({status:V(`connected`),url:k(),certificate:rf}),F({status:V(`missing-certificate`),url:k(),certificate:rf}),F({status:V(`stopped`),reason:B([`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 of=B([`official`,`self-hosted`]);F({secret:k().min(1),lastUsedAt:j().nullable(),networkUrls:P($d),directCandidates:P($d).optional(),tailscale:ef,background:nf.optional(),relay:F({state:af,enabled:N(),kind:of,officialHost:k(),customHost:k().optional(),officialHostname:k().optional(),customHostname:k().optional(),quotaUntil:k().optional()}).strict().optional()}).strict();let sf=I({threadId:k().min(1).max(1024),view:B([`result`,`messages`]),from:j().int().min(1).max(2**53-1).optional(),to:j().int().min(1).max(2**53-1).optional()}),cf=/^[a-zA-Z0-9_-]{1,64}$/u,Y=k().regex(cf),lf=k().regex(cf),uf=k().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),df=B([`relay`,`tailscale`,`lan`,`custom`]),ff=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],pf=B(ff);new Set(ff);let mf=B([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]),hf=F({peerId:Y,hostId:uf,nodeId:lf.optional(),name:k().min(1).max(120),color:pf.optional(),origin:k().min(1).max(2048),transportKind:df,encrypted:N(),enabled:N(),state:mf,supportsPeerPairing:N().optional(),pairedBack:N().optional(),linkedPeerIds:P(Y).max(128).optional(),latencyMs:j().int().nonnegative().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),lastError:k().max(1e3).optional(),projectCount:j().int().nonnegative(),createdAt:k(),updatedAt:k()});F({localPlatform:k().max(64).optional(),peers:P(hf)}),F({connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),name:k().trim().min(1).max(120).optional(),color:pf.optional(),pairBack:N().optional(),meshPeerIds:P(Y).max(64).optional(),selfOrigin:k().min(1).max(2048).optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),I({origin:k().min(1).max(2048),token:k().min(1).max(2048),name:k().trim().min(1).max(120).optional(),color:pf.optional(),expectedNodeId:lf.optional()}),F({status:B([`added`,`updated`,`existing`]),peerId:Y,hostId:uf,nodeId:lf.optional()});let gf=B([`added`,`updated`,`existing`,`failed`,`skipped`]);F({results:P(F({targetPeerId:Y,targetName:k().min(1).max(120),introducedHost:L([V(`local`),Y]),introducedName:k().min(1).max(120),status:gf,error:k().max(1e3).optional()}))}),F({peerIds:P(Y).max(64).optional(),includeSelf:N().optional(),includeMesh:N().optional(),selfOrigin:k().min(1).max(2048).optional()}),F({peerId:Y,name:k().trim().min(1).max(120).optional(),color:pf.nullable().optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),enabled:N().optional()}),F({peerId:Y}),F({removed:N()}),F({peerId:Y.optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let _f=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});F({ok:N(),nodeId:lf.optional(),supportsPeerPairing:N().optional(),pairedBack:N().optional(),latencyMs:j().int().nonnegative().optional(),origin:k().max(2048).optional(),transportKind:df.optional(),encrypted:N().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),projectCount:j().int().nonnegative().optional(),projects:P(_f).optional(),error:k().max(1e3).optional()});let vf=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192),threadIds:P(k().min(1).max(1024))}),yf=F({attachments:V(1).optional(),workspaceFiles:V(1).optional(),officePreview:V(1).optional(),delegation:V(1).optional(),peerPairing:V(1).optional()}),bf=F({version:k().max(128),platform:k().max(64),hostname:k().max(255),homeDir:k().max(4096).optional(),epoch:k().min(1).max(256),nodeId:lf.optional(),peerNodes:z(uf,lf).refine(e=>Object.keys(e).length<=128).optional(),projects:P(vf),capabilities:yf.optional()});I({threadId:k().min(1).max(1024),scope:k().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u).optional(),requestId:k().min(1).max(256).optional(),mode:B([`queue`,`steer`]).optional(),expectedTurnId:k().min(1).max(1024).nullable().optional(),content:P(R(`type`,[I({type:V(`text`),text:k()}),I({type:V(`file`),receiptId:k().min(1).max(128)})])).min(1).max(64)});let xf=F({ok:V(!1),error:F({code:k(),message:k(),details:z(k(),vc()).optional()})});L([F({ok:V(!0),value:F({receiptId:k().min(1),file:F({attachmentId:k(),name:k(),bytes:j().int().nonnegative()})})}),xf]),L([F({ok:V(!0),value:F({accepted:V(!0)})}),xf]);let Sf=F({name:k().min(1).max(512),path:k().min(1).max(8192),kind:V(`directory`)});F({peerId:Y,path:k().min(1).max(8192).optional()}),F({path:k().min(1).max(8192),parentPath:k().min(1).max(8192).nullable(),homeDir:k().min(1).max(8192).optional(),entries:P(Sf)}),F({peerId:Y,parentPath:k().min(1).max(8192),name:k().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),F({path:k().min(1).max(8192),name:k().min(1).max(255)}),F({peerId:Y,path:k().min(1).max(8192),title:k().trim().min(1).max(255).optional()}),F({peerId:Y,workspaceId:k().min(1).max(1024),title:k().trim().min(1).max(255)}),F({peerId:Y,workspaceId:k().min(1).max(1024)}),F({workspaceId:k().min(1).max(1024).optional(),manifest:bf}),F({sessionHostId:k().min(1).max(128).optional()}),F({hosts:P(F({hostId:L([V(`local`),uf]),name:k().min(1).max(120),isLocal:N().optional(),color:pf.optional(),hostname:k().max(255).optional()}))}),F({hostId:L([V(`local`),uf])}),F({harnesses:P(F({id:k().regex(/^[a-z0-9][a-z0-9-]*$/u),name:k().min(1).max(120)}))});let Cf=B([`listHarnesses`,`inspect`,`start`,`send`,`cancel`,`read`,`answer`,`list`]);I({operation:Cf,hopCount:j().int().min(0).max(16),sourceId:Y.optional(),input:ul});let wf=I({code:k().min(1).max(128),message:k().max(4096),details:ul.optional()});L([I({ok:V(!0),value:H}),I({ok:V(!1),error:wf})]);let Tf=I({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});I({hosts:P(I({hostId:uf,nodeId:lf.optional(),displayName:k().min(1).max(120),online:N(),state:mf,delegation:N(),projects:P(Tf),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional()}))}),I({version:V(1),instanceId:k().min(1).max(128),pid:j().int().positive(),endpoint:k().min(1).max(256),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j().int().nonnegative()}),L([I({operation:V(`hosts`)}),I({operation:Cf,hostId:uf,hopCount:j().int().min(0).max(16),timeoutMs:j().int().min(1).max(12e4).optional(),input:ul})]);let Ef=F({id:k().min(1).max(256),harnessId:k().min(1),label:k().min(1).max(512),provider:B([`openai-codex`,`xai`])}).strict(),Df=k().regex(/^[a-z][a-z0-9-]{0,47}$/),Of=F({name:Df,source:Ef,importedAt:k()}).strict(),kf=R(`action`,[F({action:V(`list`)}).strict(),F({action:V(`import`),sourceId:k().min(1).max(256),name:Df,confirmed:V(!0)}).strict(),F({action:V(`reimport`),sourceId:k().min(1).max(256),name:Df,confirmed:V(!0)}).strict(),F({action:V(`remove`),name:Df,confirmed:V(!0)}).strict()]),Af=F({provider:k().min(1).max(128),type:B([`oauth`,`api_key`,`unknown`]),label:k().min(1).max(512).optional(),vendor:B([`openai-codex`,`xai`]).optional()}).strict();F({sources:P(Ef),targets:P(F({harnessId:k(),providers:P(B([`openai-codex`,`xai`])),imports:P(Of),others:P(Af).default([])}).strict())}).strict(),F({targetHarnessId:k().min(1).max(128).optional(),request:kf}).strict(),F({events:N()});let jf=P(I({agent:k().min(1).max(128),section:B([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);I({entries:jf.nullable()}),I({}),I({entries:jf,initializeOnly:N().optional()});let Mf=I({enabled:N(),timeoutMinutes:j().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let Nf=k().regex(/^external$/u),Pf=U.transform(e=>String(e)),Ff=I({model:K.optional(),thinkingOptionId:q.optional(),permissionModeId:yl.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),If=I({lastHarness:U.optional(),byHarness:z(Pf,Ff)}),Lf=I({model:K.optional(),thinkingOptionId:q.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Rf=I({byHarness:z(Pf,Lf)}),zf=k().min(1).max(1024),Bf=I({idleRelease:Mf.optional(),favorites:z(Pf,P(zf).max(2048)).default({}),newThread:If.optional(),delegation:Rf.optional()});I({scope:Nf,revision:j().int().nonnegative(),values:Bf}),I({scope:Nf.default(`external`)});let Vf=R(`kind`,[I({kind:V(`idleRelease`),value:Mf}),I({kind:V(`favorite`),harnessId:U,modelId:zf,enabled:N()}),I({kind:V(`favorites`),harnessId:U,modelIds:P(zf).max(2048)}),I({kind:V(`newThread`),lastHarness:U.optional(),harnessId:U.optional(),configuration:Ff.optional()}),I({kind:V(`delegation`),harnessId:U,configuration:Lf.nullable()})]);I({scope:Nf.default(`external`),operations:P(Vf).min(1).max(256),initializeOnly:N().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`})}),I({version:V(1),revision:j().int().nonnegative(),scopes:z(Nf,Bf)});let Hf=j().finite().nonnegative(),Uf=I({input:Hf,output:Hf,cacheRead:Hf.optional(),cacheWrite:Hf.optional(),cacheWrite1h:Hf.optional()}),Wf=k().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);I({path:k(),entries:P(I({key:k(),price:Uf})),error:k().nullable()}),I({}),I({key:Wf,price:Uf.nullable(),previousKey:Wf.optional()}),I({model:Wf});let Gf=I({official:N().optional(),canonicalModelId:k().min(1).optional(),provider:k().min(1).max(512),model:k().min(1).max(512),price:Uf});I({price:Uf.nullable(),suggestions:P(Gf).max(6).optional()});let Kf=[`today`,`7d`,`30d`,`90d`,`all`],X=j().int().min(0).max(2**53-1),qf=k().regex(/^\d{4}-\d{2}-\d{2}$/u),Jf=k().min(1).max(128),Yf=k().min(1).max(512),Xf=k().min(1).max(4096);I({range:B(Kf),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:Jf.optional(),model:Yf.nullable().optional(),project:Xf.nullable().optional(),date:qf.optional()});let Zf=I({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}),Qf=Zf.shape,$f=I({harness:Jf,sessionId:k().min(1).max(512),project:Xf.nullable(),title:k().min(1).max(200).optional(),models:P(Yf).max(16),firstAtMs:X,lastAtMs:X,...Qf});I({range:B(Kf),from:qf.nullable(),to:qf,filters:I({harness:Jf.nullable(),model:Yf.nullable(),unknownModel:N(),project:Xf.nullable(),unknownProject:N(),date:qf.nullable()}),reading:I({complete:N(),sources:X,read:X}),failures:P(I({harness:Jf,message:k().max(2048)})).max(256),options:I({harnesses:P(Jf).max(256),models:P(Yf.nullable()).max(4096),projects:P(Xf.nullable()).max(4096)}),modelLabels:P(I({harness:Jf,model:Yf,label:Yf})).max(4096).optional(),credits:P(I({harness:Jf,model:Yf.nullable(),credits:j().finite().min(0),reportedRequests:X,requests:X})).max(4096).optional(),totals:Zf,daily:P(I({date:qf,harness:Jf,...Qf})).max(2e5),hourly:P(I({weekday:j().int().min(0).max(6),hour:j().int().min(0).max(23),...Qf})).max(168),byHarness:P(I({harness:Jf,...Qf})).max(256),byModel:P(I({model:Yf.nullable(),...Qf,harnessPricedRequests:X})).max(4096),byProject:P(I({project:Xf.nullable(),...Qf})).max(4096),sessions:P($f).max(100),recentSessions:P($f).max(100).optional()}),F({threadId:W}),F({discarded:N()});let ep=R(`type`,[F({id:k().min(1),type:V(`choice`),prompt:k(),options:P(F({value:k().min(1),label:k(),description:k().optional()})).min(1),multiple:N(),allowOther:N(),optional:N()}),F({id:k().min(1),type:V(`text`),prompt:k(),multiline:N(),secret:V(!1),optional:N(),placeholder:k().optional(),prefill:k().optional()})]),tp=F({interactionId:k().min(1),turnId:k().min(1),title:k().optional(),questions:P(ep).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});I({threadId:k().min(1)}),F({questions:P(tp)}),I({threadId:k().min(1),turnId:k().min(1),interactionId:k().min(1),answers:z(k(),P(k())),cancelled:N().default(!1)}),F({accepted:V(!0)});let np=`codexhostActiveTurnId`,rp=/* @__PURE__ */ new Set([np,`codexhostTurnChanges`,`codexhostToolOutput`,`codexGoal`]),ip=F({path:k(),oldText:k().nullable(),newText:k()});F({sessionId:k().min(1),turn:j().int().nonnegative(),path:k().min(1).optional()}),F({diffs:P(ip)}),I({}),I({}),F({reference:F({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()}),I({title:k().trim().min(1).max(200),type:B([`info`,`warning`,`danger`]),body:k().trim().min(1).max(16384)}),I({}),I({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.codexhost/update/macos-signing/status.codexhost/update/macos-signing/setup.codexhost/update/macos-signing/remove`.split(`.`));let ap=B([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),op=B([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);I({threadId:k(),title:k(),harnessId:k(),state:ap,reason:op,inactiveMs:j().nonnegative()}),I({threadId:W,turnId:_l});let sp=F({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:Pl.optional(),balance:Fl.optional()}).strict();function cp(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 lp=cp(sp),up={harnessId:U,harnessName:k().trim().min(1).max(128)},dp=F(up).strict();F({}).strict(),F({sources:P(dp).max(128)}).strict(),F({harnessId:U,refresh:N().optional()}).strict(),F({...up,account:lp.nullable(),accounts:P(lp).max(8).optional()}).strict(),F({refresh:N().optional()}).strict(),F({accounts:P(cp(sp.extend(up))).max(128)}).strict(),F({harnessId:eu,model:K.optional(),thinkingOptionId:q.optional(),permissionModeId:yl.optional(),prewarm:V(!0).optional()}).strict();let fp=k().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);F({harnessId:eu}).strict().extend({path:fp.nullable()}),F({path:fp.nullable(),restartRequired:N()}).strict(),F({harnessId:U,action:B([`check`,`update`,`install`]),confirmedVersion:k().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let pp=F({currentVersion:k().min(1).max(128),latestVersion:k().min(1).max(128),updateAvailable:N(),canUpdate:N(),latestVerifiedVersion:k().min(1).max(128).optional(),confirmationRequired:V(!0).optional(),versionKind:B([`cli`,`application`]).optional(),manualUpdateUrl:Xs().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:hl.optional(),latestVersionKind:B([`unknown`,`tracking-branch`]).optional()}).strict();F({taskId:k().uuid()}).strict(),R(`status`,[F({taskId:k().uuid(),status:V(`running`)}).strict(),F({taskId:k().uuid(),status:V(`succeeded`),result:pp}).strict(),F({taskId:k().uuid(),status:V(`failed`),error:F({code:j().int(),message:k().min(1).max(2048)}).strict()}).strict()]);let mp=k().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),hp=k().trim().min(1),gp=B([`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`]),_p=F({accountId:mp,label:hp.max(256),email:k().email().max(320).optional(),planType:gp.optional()}).strict(),vp=B([`ready`,`unavailable`]);F({version:V(2),currentAccountId:mp.nullable(),phase:vp,revision:j().int().nonnegative(),instanceId:hp.max(1024).optional(),accounts:P(_p).max(1)}).strict(),F({accountId:mp,refresh:N().optional()}).strict(),F({accountId:mp,usage:Ol.nullable(),accountCredits:Pl.optional(),freshness:B([`live`,`cached`]),observedAt:k().datetime().nullable()}).strict();let yp=1e3,bp=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),xp=bp.max(1024),Sp=F({nativeSessionId:xp,title:bp.max(4096).nullable(),updatedAt:j().int().nonnegative().max(864e13),cwd:bp.max(16384),running:N().nullable()}).strict();F({}).strict(),F({harnesses:P(F({harnessId:eu,name:bp.max(128)}).strict()).max(128)}).strict(),F({harnessId:eu,query:k().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:j().int().nonnegative().safe().optional(),limit:j().int().min(1).max(yp).optional()}).strict(),F({candidates:P(Sp).max(yp),total:j().int().nonnegative().safe()}).strict(),F({harnessId:eu,nativeSessionId:xp}).strict(),F({threadId:bp.max(1024).pipe(W)}).strict();let Cp=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),wp=xp,Tp=Sp;F({}).strict(),F({candidates:P(Tp).max(1e3)}).strict(),F({nativeSessionId:wp}).strict(),F({threadId:Cp.max(1024).pipe(W)}).strict(),F({threadId:W,lastTurnId:_l}).strict(),F({threadId:W}).strict();let Ep=k().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();F({commands:P(F({id:Ep,invocation:k().min(1).max(128),label:k().trim().min(1).max(128),description:k().trim().min(1).max(512).optional(),localizations:ml.optional(),argumentMode:B([`none`,`text`]),kind:B([`command`,`skill`]).optional()}).strict()),warnings:P(k().min(1)).optional(),source:B([`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)}),F({harnessId:U,cwd:k().min(1).optional()}).strict(),F({threadId:W}).strict(),F({threadId:W,commandId:Ep,turnId:_l.optional(),arguments:ul.optional()}).strict(),F({accepted:V(!0),turnId:_l.optional()}).strict();let Dp=V(`2.0`).optional(),Z=bc().optional(),Op=k().min(1),kp=L([k(),j().int()]),Ap=F({code:j().int(),message:k(),data:H.optional()}).catchall(H).superRefine(al([`data`]));L([F({jsonrpc:Dp,id:kp,method:Op,params:H.optional(),result:Z,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`params`,`result`,`error`])),F({jsonrpc:Dp,id:Z,method:Op,params:H.optional(),result:Z,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`id`,`params`,`result`,`error`])),F({jsonrpc:Dp,id:kp,method:Z,params:Z,result:H,error:Z}).catchall(H).superRefine(al([`jsonrpc`,`method`,`params`,`error`])),F({jsonrpc:Dp,id:kp,method:Z,params:Z,result:Z,error:Ap}).catchall(H).superRefine(al([`jsonrpc`,`method`,`params`,`result`]))]);let jp=k().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});I({harnessId:U,nativeSessionId:jp,locator:H.optional(),formatVersion:V(1)}).superRefine(al([`locator`])),I({harnessId:U,nativeSessionId:jp,nativeTurnKey:jp,formatVersion:V(1)}),I({harnessId:U,nativeSessionId:jp,checkpointId:jp,locator:H.optional(),formatVersion:V(1)}).superRefine(al([`locator`]));let Mp=k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Np=B([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Pp=B([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),Fp=I({completed:j().int().nonnegative(),total:j().int().positive()}).refine(e=>e.completed<=e.total,{path:[`completed`],message:`completed must not exceed total`}),Ip=I({version:Mp,installation:Np,phase:Pp,updatedAt:j().int().nonnegative(),downloadedBytes:j().int().nonnegative().optional(),totalBytes:j().int().positive().optional(),npmDownload:Fp.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`})});I({});let Lp=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`),Rp=B([`idle`,`downloading`,`ready`,`failed`]),zp=I({downloadedBytes:j().int().nonnegative(),totalBytes:j().int().positive()}).refine(e=>e.downloadedBytes<=e.totalBytes,{path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`});F({currentVersion:Mp,installation:Np.nullable(),latestVersion:Mp.nullable(),updateAvailable:N(),installationAvailable:N(),releaseNotes:k().min(1).max(2e4).nullable(),releaseNotesUrl:Lp.nullable(),status:Ip.nullable(),error:k().min(1).max(500).nullable(),stagedVersion:Mp.nullable().optional(),backgroundPhase:Rp.optional(),backgroundDownload:zp.nullable().optional(),backgroundError:k().min(1).max(500).nullable().optional(),runningTaskCount:j().int().nonnegative().optional()}),I({status:Ip}),I({status:Ip.nullable()}),I({supported:N(),enabled:N(),certificatePresent:N(),appSignedWithLocalCert:N(),appPath:k().min(1).nullable(),certificateName:k().min(1),certificateSha1:k().regex(/^[0-9A-Fa-f]{40}$/u).nullable()});let Bp=I({icon:k().min(1).max(16).optional(),title:k().min(1).max(120),body:k().min(1).max(1200),contributors:P(k().min(1).max(39)).max(30)}),Vp=I({summary:k().min(1).max(600).optional(),themes:P(Bp).min(1).max(12)}),Hp=I({version:Mp,publishedAt:il(),url:k().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Vp.nullable(),en:Vp.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});I({manual:N().optional()}),I({announcement:Hp.nullable(),unread:N()}),I({version:Mp}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Up=B([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);F({runningVersion:k().nullable(),installedVersion:k().nullable(),restartRequired:N(),remote:N(),updateSupported:N(),update:F({phase:Up,targetVersion:k().nullable(),error:k().nullable()})});let Wp=F({version:k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();F({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:B([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:N().optional(),version:k().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),F({state:B([`installed`,`not-installed`])}).strict();let Q=k().min(1).max(1024),Gp={hostId:Q.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},$={...Gp,threadId:Q},Kp=k().min(1).max(8e3),qp={text:Kp,requestId:Q};R(`accepted`,[F({accepted:V(!0),startQueuedItemId:Q.optional()}),F({accepted:V(!1),code:B([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:k()})]),R(`available`,[F({available:V(!1)}),F({available:V(!0),items:P(F({id:Q,clientUserMessageId:Q,preview:k().max(801)})).max(100)})]);let Jp=R(`kind`,[I({kind:V(`hosts`)}),I({kind:V(`create`),...Gp,cwd:k().min(1).max(8192),epoch:Q}),I({kind:V(`projectHarnesses`),...Gp,epoch:Q}),I({kind:V(`inspectHarness`),...Gp,epoch:Q,cwd:k().min(1).max(8192),harnessId:Q}),I({kind:V(`startSelected`),...Gp,epoch:Q,cwd:k().min(1).max(8192),harnessId:Q,model:k().min(1).max(4096),serviceTier:B([`priority`,`ultrafast`]).optional(),reasoningEffort:Q.optional()}),I({kind:V(`status`),...$}),I({kind:V(`list`),...Gp,cursor:k().nullable(),archived:N(),includeLoaded:V(!0).optional()}),I({kind:V(`read`),...$,page:I({cursor:k().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:B([`asc`,`desc`]).optional(),limit:j().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),I({kind:V(`usage`),...$,epoch:Q}),I({kind:V(`configure`),...$,epoch:Q,modelId:Q.optional(),serviceTier:Rl.optional(),thinkingOptionId:Q.optional(),permissionModeId:Q.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),I({kind:V(`prompt`),...$,epoch:Q,text:Kp,requestId:Q.optional()}),I({kind:V(`queue`),...$,epoch:Q}),I({kind:V(`delivery`),...$,epoch:Q,action:R(`kind`,[I({kind:V(`enqueue`),...qp}),I({kind:V(`steer`),...qp,turnId:Q}),I({kind:V(`remove`),itemId:Q}),I({kind:V(`start`),itemId:Q,onlyIfHead:V(!0).optional()}),I({kind:V(`sendNow`),itemId:Q})])}),I({kind:V(`interrupt`),...$,epoch:Q,turnId:Q}),I({kind:V(`rename`),...$,epoch:Q,name:k().min(1).max(512)}),I({kind:V(`archive`),...$,epoch:Q,archived:N()}),I({kind:V(`respond`),...$,epoch:Q,requestId:L([Q,j().int()]),result:z(k(),vc())})]),Yp=k().min(1).max(1024),Xp=F({hostId:Yp,displayName:k().min(1).max(1024),source:B([`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:N(),connectionAnalyticsId:k().max(1024).optional()}),Zp=I({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()});R(`action`,[I({action:V(`session`),operation:Jp}),I({action:V(`list`)}),I({action:V(`catalog`)}),I({action:V(`read-thread`),hostId:Yp.refine(e=>e!==`local`),input:sf}),I({action:V(`save`),draft:Zp,previous:Xp.nullable()}),I({action:V(`remove`),previous:Xp}),I({action:V(`connect`),hostId:Yp,enabled:N()}),I({action:V(`state`),hostId:Yp}),I({action:V(`runtime`),hostId:Yp}),I({action:V(`update`),hostId:Yp.refine(e=>e!==`local`),version:Wp.shape.version})]),L([I({result:H}),I({error:I({code:j().int(),message:k()})})]),I({prompt:k().trim().min(1).max(2e3),cwd:k().max(4096).nullable()}),k().trim().min(1).max(60).nullable();let Qp=k().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),$p=L([k(),F({en:k()}).catchall(k())]),em=F({title:$p.optional(),description:$p.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()});F({extensions:P(F({id:Qp,name:k().min(1).max(214),version:k().min(1).max(128),format:V(`dsh`),supportedTargets:Oc([V(`web`)]),enabledTargets:P(V(`web`)).max(1),source:k().min(1).max(4096),projectUrl:k().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:k(),meta:em.optional(),loadError:k().optional()})),loadedIds:P(Qp),safeMode:N(),storeError:k().optional()});let tm=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}/`);F({spec:k().trim().min(1).max(4096),registry:tm.optional()}).strict(),F({id:Qp,enabled:N()}).strict(),F({id:Qp}).strict(),V(1);function nm(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];
|
|
114
114
|
/* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
|
|
115
|
-
if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let
|
|
116
|
-
`,r:`\r`,t:` `},
|
|
117
|
-
`||e===`\r`||e===` `}function
|
|
115
|
+
if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let rm={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
|
|
116
|
+
`,r:`\r`,t:` `},im=/[\\\u0000-\u001f]/u;function am(e){return e===` `||e===`
|
|
117
|
+
`||e===`\r`||e===` `}function om(e){return e>=`0`&&e<=`9`||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}(class e{static EMPTY=e.fromObject({});static fromText(t){let n=new e;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new e;return n.object=typeof t==`object`&&t&&!Array.isArray(t)?t:{},n.sealed=!0,n}chunks=[];object;sealed=!1;#e=[];#t=0;#n=0;#r=`root`;#i=!1;#a=0;#o=!1;#s=``;#c=null;#l=[];#u=!1;#d;#f=!1;#p=/* @__PURE__ */ new Map;#m=[];#h=/* @__PURE__ */ new Map;get isSealed(){return this.sealed}get invalid(){return this.scan(),this.#r===`invalid`||this.#f}append(e){if(this.sealed)throw Error(`PartialArguments: cannot append to a sealed view`);e.length!==0&&(this.chunks.push(e),this.#t+=e.length,this.#e.push(this.#t))}settle(t){if(this.object!==void 0||t.length!==this.#t)return e.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return e.fromText(t);n+=r.length}return this.chunks=t.length===0?[]:[t],this.#e=t.length===0?[]:[t.length],this.sealed=!0,this}refresh(){if(this.#h.size===0)return!1;this.scan();let e=!1,t=!1;for(let n of this.#h.values())n.completion?t=!0:e=this.refreshRead(n)||e;if(t)for(let t of this.#h.values())t.completion&&(e=this.refreshRead(t)||e);return this.sealed&&this.#h.clear(),e}refreshRead(e){let t=e.answer();return!Object.is(t,e.last)&&(e.last=t,!0)}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),e=>e.length)}has(e){return this.remember(`has`,e,()=>this.hasNow(e))}complete(e){return this.remember(`complete`,e,()=>this.completeNow(e))}stringLength(e,t){let n=Math.max(1,Math.floor(t?.step??1)),r=t?.offset??0;return this.remember(`length:${n}:${r}`,e,()=>this.lengthNow(e),e=>e===void 0?void 0:Math.ceil((e+r)/n))}stringExceeds(e,t){let n=Math.max(0,Math.floor(t));return this.remember(`exceeds:${n}`,e,()=>(this.lengthNow(e,n+1)??0)>n)}text(e){return this.remember(`text`,e,()=>this.textNow(e))}textPrefix(e,t){let n=Math.max(1,Math.floor(t));return this.remember(`prefix:${n}`,e,()=>this.textPrefixNow(e,n))}value(e){return this.remember(`value`,e,()=>this.valueNow(e))}remember(e,t,n,r){this.scan();let i=n();if(!this.sealed){let a=`${e}/${t}`;this.#h.has(a)||this.#h.set(a,{completion:e===`complete`,answer:r===void 0?n:()=>r(n()),last:r===void 0?i:r(i)})}return i}closedNow(){return this.sealed||this.#r===`closed`||this.#r===`invalid`}keysNow(){return this.object===void 0?this.#m:Object.keys(this.object)}hasNow(e){return this.object===void 0?this.#p.has(e):Object.hasOwn(this.object,e)}completeNow(e){if(this.object!==void 0)return Object.hasOwn(this.object,e);let t=this.#p.get(e);return t!==void 0&&t.end>=0&&(t.kind===`string`?t.invalidAt===void 0:!t.invalid)}lengthNow(e,t=1/0){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t.length:void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;if(n.text!==void 0&&n.text.at===n.end)return n.text.length;let r=n.length??={at:n.start,length:0,text:``};return this.readString(n,r,t,!1),r.length}textNow(e){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t:void 0}let t=this.#p.get(e);if(t?.kind!==`string`)return;if(t.text===void 0&&t.end>=0&&t.needsDecoding&&t.invalidAt===void 0){let e;try{e=JSON.parse(`"${this.slice(t.start,t.end)}"`)}catch{}e!==void 0&&(t.text={at:t.end,length:e.length,text:e})}let n=t.text??={at:t.start,length:0,text:``};return this.readString(t,n,1/0,!0),n.text}textPrefixNow(e,t){if(this.object!==void 0){let n=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof n==`string`?n.slice(0,t):void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;let r=n.prefixes??=/* @__PURE__ */ new Map,i=r.get(t);return i===void 0&&(i={at:n.start,length:0,text:``},r.set(t,i)),this.readString(n,i,t,!0),i.text}valueNow(e){if(this.object!==void 0){if(!Object.hasOwn(this.object,e))return;let t=this.object[e];return typeof t==`string`?void 0:t}let t=this.#p.get(e);if(!(t?.kind!==`value`||t.end<0||t.invalid)){if(t.parsed===void 0)try{t.parsed=JSON.parse(this.slice(t.start,t.end))}catch{t.invalid=!0,this.#f=!0}return t.parsed}}chunkAt(e){let t=0,n=this.#e.length;for(;t<n;){let r=t+n>>>1;this.#e[r]<=e?t=r+1:n=r}return t}slice(e,t){if(e>=t)return``;let n=this.chunkAt(e),r=this.chunkAt(t-1),i=n===0?0:this.#e[n-1];if(n===r)return this.chunks[n].slice(e-i,t-i);let a=[this.chunks[n].slice(e-i)];for(let e=n+1;e<r;e++)a.push(this.chunks[e]);return a.push(this.chunks[r].slice(0,t-this.#e[r-1])),a.join(``)}readString(e,t,n,r){let i=Math.min(e.end<0?this.#n:e.end,e.invalidAt??1/0,this.#d??1/0);if(!e.needsDecoding){let e=Math.min(i-t.at,n-t.length);if(e<=0)return;r&&(t.text+=this.slice(t.at,t.at+e)),t.at+=e,t.length+=e;return}let a=this.chunkAt(t.at);for(;t.at<i&&t.length<n;){let o=a===0?0:this.#e[a-1],s=this.chunks[a],c=s.slice(t.at-o,Math.min(s.length,i-o)),l=c.search(im),u=Math.min(l<0?c.length:l,n-t.length);if(u>0){r&&(t.text+=c.slice(0,u)),t.at+=u,t.length+=u,t.at===o+s.length&&a++;continue}let d=c.length>1?c[1]:t.at+1<i?this.chunks[a+1][0]:void 0,f,p=2;if(c[0]===`\\`&&d===void 0&&e.end<0)return;if(c[0]===`\\`&&d===`u`){let n=this.slice(t.at+2,Math.min(i,t.at+6)),r=!0;for(let e=0;e<n.length;e++)om(n[e])||(r=!1);if(r){if(n.length<4&&e.end<0)return;n.length===4&&(f=String.fromCharCode(Number.parseInt(n,16)))}p=6}else c[0]===`\\`&&d!==void 0&&(f=rm[d]);if(f===void 0){e.invalidAt=t.at,this.#f=!0;return}for(r&&(t.text+=f),t.length++,t.at+=p;a<this.chunks.length&&t.at>=this.#e[a];)a++}}scan(){if(this.object===void 0&&this.#n!==this.#t)for(let e=this.chunkAt(this.#n);e<this.chunks.length&&this.#d===void 0;e++){let t=this.chunks[e],n=e===0?0:this.#e[e-1];for(let e=this.#n-n;e<t.length&&this.#r!==`invalid`;e++){if(this.#r===`string`||this.#r===`nested`&&this.#u){let n=this.stringBoundary(t,e);if(this.#n+=n-e,e=n,e===t.length)break}this.step(t[e],this.#n),this.#n++}}}stringBoundary(e,t){let n=t;for(;;){let t=e.indexOf(`"`,n),r=t<0?e.length:t;if(this.#r===`string`){let t=this.#c;!t.needsDecoding&&im.test(e.slice(n,r))&&(t.needsDecoding=!0)}let i=r;for(;i>n&&e[i-1]===`\\`;)i--;let a=(r-i)%2==1!==(i===n&&this.#i);if(this.#i=t<0&&a,t<0||!a)return r;n=t+1}}step(e,t){switch(this.#r){case`root`:if(am(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(am(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(am(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(am(e))return;if(e===`:`){this.#r=`value`;return}this.fail();return;case`value`:this.beginValue(e,t);return;case`string`:{let e=this.#c;e.end=t,this.#c=null,this.#r=`comma-or-end`;return}case`scalar`:this.stepScalar(e,t);return;case`nested`:this.stepNested(e,t);return;case`comma-or-end`:if(am(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(am(e))return;this.fail();return;
|
|
118
118
|
/* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
|
|
119
119
|
case`invalid`:return;
|
|
120
120
|
/* v8 ignore next 2 -- Every scanner mode has a handler above. */
|
|
121
|
-
default:
|
|
121
|
+
default:sm(this.#r)}}fail(){this.#d=this.#n,this.#r=`invalid`,this.#c=null}beginKey(e){this.#r=`key`,this.#a=e+1,this.#o=!1,this.#i=!1}stepKey(e,t){if(e<` `){this.fail();return}if(this.#i){this.#i=!1;return}if(e===`\\`){this.#i=!0,this.#o=!0;return}if(e!==`"`)return;let n=this.slice(this.#a,t);if(this.#o)try{this.#s=JSON.parse(`"${n}"`)}catch{this.fail();return}else this.#s=n;this.#r=`colon`}open(e){this.#p.has(this.#s)||this.#m.push(this.#s),this.#p.set(this.#s,e),this.#c=e}beginValue(e,t){am(e)||(e===`"`?(this.open({kind:`string`,start:t+1,end:-1,needsDecoding:!1,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0}),this.#i=!1,this.#r=`string`):e===`}`||e===`,`||e===`:`||e===`]`?this.fail():(this.open({kind:`value`,start:t,end:-1,parsed:void 0,invalid:!1}),e===`{`||e===`[`?(this.#r=`nested`,this.#l=[e===`{`?`}`:`]`],this.#u=!1,this.#i=!1):this.#r=`scalar`))}stepScalar(e,t){(e===`,`||e===`}`||am(e))&&(this.closeValue(t),this.#r=e===`,`?`key-only`:e===`}`?`closed`:`comma-or-end`)}stepNested(e,t){if(this.#u)this.#u=!1;else if(e===`"`)this.#u=!0;else if(e===`{`||e===`[`)this.#l.push(e===`{`?`}`:`]`);else if(e===`}`||e===`]`){if(this.#l.pop()!==e){this.fail();return}this.#l.length===0&&(this.closeValue(t+1),this.#r=`comma-or-end`)}}closeValue(e){let t=this.#c;t.end=e,this.#c=null}});function sm(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function cm(e,t){let n=Object.getOwnPropertyDescriptor(e,`constructor`)?.value;if(typeof n!=`function`)return!1;try{return n.name===t&&n.prototype===e&&Function.prototype.toString.call(n)===Function.prototype.toString.call(t===`Array`?Array:Object)}catch{return!1}}function lm(e){return Object.getPrototypeOf(e)===null&&cm(e,`Object`)}function um(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!cm(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&lm(n)}function dm(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&lm(t)}function fm(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function pm(e,t){let n=/* @__PURE__ */ new Set,r,i=(e,t)=>{e!==void 0&&(e.kind===`root`?r=t:e.kind===`array`?e.target[e.index]=t:Object.defineProperty(e.target,e.key,{value:t,enumerable:!0,configurable:!0,writable:!0}))},a=[{kind:`visit`,value:e,...t?{destination:{kind:`root`}}:{}}];for(let e=a.pop();e!==void 0;e=a.pop()){if(e.kind===`leave`){n.delete(e.source);continue}if(e.kind===`array-item`){if(!Object.prototype.hasOwnProperty.call(e.source,e.index))return;a.push({kind:`visit`,value:e.source[e.index],...e.target===void 0?{}:{destination:{kind:`array`,target:e.target,index:e.index}}});continue}if(e.kind===`object-property`){a.push({kind:`visit`,value:e.source[e.key],...e.target===void 0?{}:{destination:{kind:`object`,target:e.target,key:e.key}}});continue}let r=e.value;if(r===null){i(e.destination,null);continue}if(typeof r==`boolean`||typeof r==`string`){i(e.destination,r);continue}if(typeof r==`number`){if(!Number.isFinite(r)||Object.is(r,-0))return;i(e.destination,r);continue}if(typeof r!=`object`||n.has(r))return;if(Array.isArray(r)){if(!um(r))return;let o=r.length;if(Reflect.ownKeys(r).length!==o+1)return;let s=t?[]:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o-1;e>=0;e--)a.push({kind:`array-item`,source:r,index:e,...s===void 0?{}:{target:s}});continue}if(!dm(r))return;let o=fm(r);if(o===void 0)return;let s=t?{}:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o.length-1;e>=0;e--){let t=o[e];
|
|
122
122
|
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
123
|
-
if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function
|
|
123
|
+
if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function mm(e){return pm(e,!0)}function hm(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
|
|
124
124
|
/* v8 ignore next -- the loop condition guarantees one pending task. */
|
|
125
125
|
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];
|
|
126
126
|
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
127
|
-
t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function lm(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 um=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]`))}};function dm(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!dm(e[n],t[n]))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.getPrototypeOf(t)||n!==Object.prototype&&n!==null)return!1;let r=e,i=t,a=Object.keys(r),o=Object.keys(i);if(a.length!==o.length)return!1;for(let e of a)if(!Object.hasOwn(i,e)||!dm(r[e],i[e]))return!1;return!0}var fm=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new um(()=>{});constructor(e){this.anyIgnoredKeys=e}get revision(){return this.writeRevision}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);return r?.kind===`sequenced`&&n<=r.seq?!1:r!==void 0&&dm(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyLive(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<r.seq?!1:r!==void 0&&dm(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyCached(e){for(let t of Object.keys(e)){let n=this.rows.get(t);n?.kind!==`sequenced`&&(n!==void 0&&dm(n.value,e[t])?this.writeRevision+=1:(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t)))}}seed(e,t,n){let r=e.values;for(let[e,t]of this.rows)t.kind!==`cached`||Object.hasOwn(r,e)||(this.rows.delete(e),this.changed(e));for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.writeRevision+=1,this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyIgnoredKeys?.has(e)||this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new um(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}};let pm=/* @__PURE__ */ new WeakMap;function mm(e){return e.length*2}function hm(e,t){return mm(e)+mm(t)+64}function gm(e){if(e===void 0||e.size===0)return 0;let t=64;for(let[n,r]of e)t+=hm(n,r);return t}function _m(e,t=0,n){if(e==null)return 0;switch(typeof e){case`string`:return mm(e);case`number`:case`boolean`:case`bigint`:case`symbol`:return 8;case`function`:return 64;case`object`:{if(t>=12)return 64;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength+64;let r=pm.get(e);if(r!==void 0)return r;if(n?.has(e))return 8;let i=n??/* @__PURE__ */ new Set;i.add(e);let a=64;try{if(Array.isArray(e)){a+=e.length*8;for(let n=0;n<e.length;n+=1)a+=_m(e[n],t+1,i)}else if(e instanceof Map)for(let[n,r]of e)a+=64+_m(n,t+1,i)+_m(r,t+1,i);else if(e instanceof Set)for(let n of e)a+=8+_m(n,t+1,i);else{let n=e;for(let e in n)Object.hasOwn(n,e)&&(a+=mm(e)+8+_m(n[e],t+1,i))}}finally{i.delete(e)}return t===0&&n===void 0&&Object.isFrozen(e)&&pm.set(e,a),a}default:return 0}}function vm(e){let t=pm.get(e);if(t!==void 0)return t;let n=_m(e);return pm.set(e,n),n}function ym(e){let t=0;for(let n=0;n<e.length;n+=1)t+=8+vm(e[n]);return t}function bm(e){return e===void 0?0:64+mm(e.epoch)+ym(e.records)}function xm(e){let t=64,n;if(e.journal!==void 0){t+=64+mm(e.journal.epoch),n=/* @__PURE__ */ new Set;for(let r of e.journal.records)t+=8+vm(r),n.add(r),typeof r.event==`object`&&r.event!==null&&n.add(r.event)}t+=64;for(let r of e.entries){if(t+=8,n!==void 0){if(n.has(r))continue;if(typeof r.event==`object`&&r.event!==null&&n.has(r.event)){t+=64;continue}}t+=vm(r)}return t+=gm(e.toolOutputs),t+=_m(e.projections),t}var Sm=class{readRemote;values=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;maxBytes;totalBytes=0;constructor(e,t,n={}){if(this.readRemote=e,this.maxBytes=Math.max(0,n.maxBytes??8388608),t!==void 0)for(let[e,n]of t)this.remember(e,n)}get estimatedBytes(){return this.totalBytes}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 this.values.delete(t),this.values.set(t,n),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.remember(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}remember(e,t){let n=this.values.get(e);n!==void 0&&(this.totalBytes-=hm(e,n),this.values.delete(e));let r=hm(e,t);if(!(r>this.maxBytes))for(this.values.set(e,t),this.totalBytes+=r;this.totalBytes>this.maxBytes&&this.values.size>0;){let t=this.values.entries().next().value;if(t[0]===e)break;this.values.delete(t[0]),this.totalBytes-=hm(t[0],t[1])}}};function Cm(){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 wm(e){return{kind:`leaf`,entries:e,length:e.length}}function Tm(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Em(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 Dm(e,t,n,r){let i;return{get entries(){return i??=Em(e),i},hasMore:t,revision:n,change:r}}var Om=class{listeners=/* @__PURE__ */ new Set;window=wm([]);estimatedEntryBytes=0;snapshot=Dm(this.window,!1,0,{kind:`replace`,entries:[]});get estimatedBytes(){return this.estimatedEntryBytes}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=wm(e),this.estimatedEntryBytes=ym(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Tm(wm(e),this.window),this.estimatedEntryBytes+=ym(e),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Tm(this.window,wm(t)),this.estimatedEntryBytes+=8+vm(e),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Em(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=wm(n),this.estimatedEntryBytes=ym(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Dm(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function km(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Am(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function jm(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 Mm(e){let t=sm(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Nm(e){let t=[];for(let n of e){let e=Pm(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 Pm(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`:{Lm(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Im(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Fm(t,e.length,t.type),t}case`tool-call-chunks`:{Lm(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Im(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 Fm(t,e.length,t.type),t}case`chunk`:{Lm(t,[`type`,`time`,`chunk`],`chunk`);let e=Am(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=Mm(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return cm({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Fm(e,t,n){if(Am(e.time0),jm(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 Im(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Lm(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 Rm=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;estimatedPendingBytes(){if(this.pending.size===0)return 0;let e=0;for(let t of this.pending.values())e+=8+vm(t);return e}replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Nm(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=zm(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function zm(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Bm(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Vm={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},Hm={...Vm,turnWindow:{...Vm.turnWindow,minMessages:200}};var Um=class{sessionId;remote;baseSeq=m(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 Rm;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionTarget;submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Om;cachedProjectionBytesRevision=-1;cachedProjectionBytes=0;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Sm(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new fm,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 um(()=>{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){if(this.submissionTarget!==void 0)return this.submissionTarget.beginSubmission(e);let t=Cm(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onObserved:e.onObserved,onRetire:e.onRetire,observed:!1,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}handoffSubmissions(e){if(e=e.submissionOwner(),e===this||this.submissionTarget!==void 0)return[];let t=this.pendingSubmissions.map(e=>e.requestId);if(t.length===0)return t;e.pendingSubmissions=[...e.pendingSubmissions,...this.pendingSubmissions];for(let n of t){let t=this.submissionSettlements.get(n);t!==void 0&&e.submissionSettlements.set(n,t);let r=this.inFlightPrompts.get(n);r!==void 0&&e.inFlightPrompts.set(n,r)}this.submissionSettlements.clear(),this.submissionTarget=e,e.promptAttempted||=this.promptAttempted;for(let{event:t}of e.eventSource.getSnapshot().entries)e.observeSubmissionEvent(t);return e.observeSubmissionInbox(),e.notifier.markDirty(),t}submissionOwner(){return this.submissionTarget?.submissionOwner()??this}get hasInFlightPrompts(){return this.inFlightPrompts.size>0}activeTurnForSteering(){let e=this.projections.get(Yf);return typeof e==`string`?e:null}async prompt(e,t,n,r){if(this.submissionTarget!==void 0)return this.submissionTarget.prompt(e,t,n,r);let i=r??Cm();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=km(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:km()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}let c=this.submissionOwner();return!s.ok&&s.error.code===`remote/outcome-unknown`&&c.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(c.acceptPrompt(),s):(r!==void 0&&c.retireFailedSubmission(r),c.promptError={op:`send`,error:s.error,requestId:i},c.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i);let e=this.submissionOwner();e.inFlightPrompts.get(i)===a&&e.inFlightPrompts.delete(i),this.notifier.markDirty()}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Vm})}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,...Hm}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}estimatedBytes(){let e=this.projections.revision;return this.cachedProjectionBytesRevision!==e&&(this.cachedProjectionBytes=_m(this.projections.values()),this.cachedProjectionBytesRevision=e),(this.eventSource.estimatedBytes>0?this.eventSource.estimatedBytes:bm(this.cachedJournal))+this.assistantStream.estimatedPendingBytes()+this.toolOutputs.estimatedBytes+this.cachedProjectionBytes}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:new Map(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(Xf),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Vm),e!==this.openGeneration||this.events!==n)return;this.cachedJournal=void 0,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:Bm(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)),e.key===`subagent`&&this.address?.mode===`unknown`&&this.notifier.markDirty()}let t=this.lastSyncedAt;this.lastSyncedAt=Date.now(),(e.type!==`assistant-stream`||t===void 0)&&this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=m(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,Xf),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);else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId);else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),t&&this.notifier.markDirty()}else e?.type===`transient`&&this.eventSource.append(e.entry)}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e);return}let n=this.hasMore;this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t),n!==t&&this.notifier.markDirty();for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:Gm(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=Gm(e.content),this.notifySubmissionObserved(i,i.admitted),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,Gm(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}notifySubmissionObserved(e,t){e.observed||(e.observed=!0,e.onObserved?.(t))}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,this.notifySubmissionObserved(n,t),Wm(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){if(this.submissionTarget!==void 0){this.submissionTarget.retireFailedSubmission(e);return}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){if(this.submissionTarget!==void 0){this.submissionTarget.finishSubmission(e,t);return}let n=this.submissionSettlements.get(e);
|
|
127
|
+
t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function gm(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 _m=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]`))}};function vm(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!vm(e[n],t[n]))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.getPrototypeOf(t)||n!==Object.prototype&&n!==null)return!1;let r=e,i=t,a=Object.keys(r),o=Object.keys(i);if(a.length!==o.length)return!1;for(let e of a)if(!Object.hasOwn(i,e)||!vm(r[e],i[e]))return!1;return!0}var ym=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new _m(()=>{});constructor(e){this.anyIgnoredKeys=e}get revision(){return this.writeRevision}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);return r?.kind===`sequenced`&&n<=r.seq?!1:r!==void 0&&vm(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyLive(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<r.seq?!1:r!==void 0&&vm(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyCached(e){for(let t of Object.keys(e)){let n=this.rows.get(t);n?.kind!==`sequenced`&&(n!==void 0&&vm(n.value,e[t])?this.writeRevision+=1:(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t)))}}seed(e,t,n){let r=e.values;for(let[e,t]of this.rows)t.kind!==`cached`||Object.hasOwn(r,e)||(this.rows.delete(e),this.changed(e));for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.writeRevision+=1,this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyIgnoredKeys?.has(e)||this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new _m(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}};let bm=/* @__PURE__ */ new WeakMap;function xm(e){return e.length*2}function Sm(e,t){return xm(e)+xm(t)+64}function Cm(e){if(e===void 0||e.size===0)return 0;let t=64;for(let[n,r]of e)t+=Sm(n,r);return t}function wm(e,t=0,n){if(e==null)return 0;switch(typeof e){case`string`:return xm(e);case`number`:case`boolean`:case`bigint`:case`symbol`:return 8;case`function`:return 64;case`object`:{if(t>=12)return 64;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength+64;let r=bm.get(e);if(r!==void 0)return r;if(n?.has(e))return 8;let i=n??/* @__PURE__ */ new Set;i.add(e);let a=64;try{if(Array.isArray(e)){a+=e.length*8;for(let n=0;n<e.length;n+=1)a+=wm(e[n],t+1,i)}else if(e instanceof Map)for(let[n,r]of e)a+=64+wm(n,t+1,i)+wm(r,t+1,i);else if(e instanceof Set)for(let n of e)a+=8+wm(n,t+1,i);else{let n=e;for(let e in n)Object.hasOwn(n,e)&&(a+=xm(e)+8+wm(n[e],t+1,i))}}finally{i.delete(e)}return t===0&&n===void 0&&Object.isFrozen(e)&&bm.set(e,a),a}default:return 0}}function Tm(e){let t=bm.get(e);if(t!==void 0)return t;let n=wm(e);return bm.set(e,n),n}function Em(e){let t=0;for(let n=0;n<e.length;n+=1)t+=8+Tm(e[n]);return t}function Dm(e){return e===void 0?0:64+xm(e.epoch)+Em(e.records)}function Om(e){let t=64,n;if(e.journal!==void 0){t+=64+xm(e.journal.epoch),n=/* @__PURE__ */ new Set;for(let r of e.journal.records)t+=8+Tm(r),n.add(r),typeof r.event==`object`&&r.event!==null&&n.add(r.event)}t+=64;for(let r of e.entries){if(t+=8,n!==void 0){if(n.has(r))continue;if(typeof r.event==`object`&&r.event!==null&&n.has(r.event)){t+=64;continue}}t+=Tm(r)}return t+=Cm(e.toolOutputs),t+=wm(e.projections),t}var km=class{readRemote;values=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;maxBytes;totalBytes=0;constructor(e,t,n={}){if(this.readRemote=e,this.maxBytes=Math.max(0,n.maxBytes??8388608),t!==void 0)for(let[e,n]of t)this.remember(e,n)}get estimatedBytes(){return this.totalBytes}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 this.values.delete(t),this.values.set(t,n),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.remember(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}remember(e,t){let n=this.values.get(e);n!==void 0&&(this.totalBytes-=Sm(e,n),this.values.delete(e));let r=Sm(e,t);if(!(r>this.maxBytes))for(this.values.set(e,t),this.totalBytes+=r;this.totalBytes>this.maxBytes&&this.values.size>0;){let t=this.values.entries().next().value;if(t[0]===e)break;this.values.delete(t[0]),this.totalBytes-=Sm(t[0],t[1])}}};function Am(){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 jm(e){return{kind:`leaf`,entries:e,length:e.length}}function Mm(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Nm(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 Pm(e,t,n,r){let i;return{get entries(){return i??=Nm(e),i},hasMore:t,revision:n,change:r}}var Fm=class{listeners=/* @__PURE__ */ new Set;window=jm([]);estimatedEntryBytes=0;snapshot=Pm(this.window,!1,0,{kind:`replace`,entries:[]});get estimatedBytes(){return this.estimatedEntryBytes}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=jm(e),this.estimatedEntryBytes=Em(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Mm(jm(e),this.window),this.estimatedEntryBytes+=Em(e),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Mm(this.window,jm(t)),this.estimatedEntryBytes+=8+Tm(e),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Nm(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=jm(n),this.estimatedEntryBytes=Em(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Pm(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Im(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Lm(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Rm(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 zm(e){let t=mm(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Bm(e){let t=[];for(let n of e){let e=Vm(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 Vm(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`:{Wm(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Um(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Hm(t,e.length,t.type),t}case`tool-call-chunks`:{Wm(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Um(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 Hm(t,e.length,t.type),t}case`chunk`:{Wm(t,[`type`,`time`,`chunk`],`chunk`);let e=Lm(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=zm(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return hm({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Hm(e,t,n){if(Lm(e.time0),Rm(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 Um(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Wm(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 Gm=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;estimatedPendingBytes(){if(this.pending.size===0)return 0;let e=0;for(let t of this.pending.values())e+=8+Tm(t);return e}replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Bm(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=Km(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function Km(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function qm(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Jm={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},Ym={...Jm,turnWindow:{...Jm.turnWindow,minMessages:200}};var Xm=class{sessionId;remote;baseSeq=m(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 Gm;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionTarget;submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Fm;cachedProjectionBytesRevision=-1;cachedProjectionBytes=0;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new km(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new ym,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 _m(()=>{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){if(this.submissionTarget!==void 0)return this.submissionTarget.beginSubmission(e);let t=Am(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onObserved:e.onObserved,onRetire:e.onRetire,observed:!1,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}handoffSubmissions(e){if(e=e.submissionOwner(),e===this||this.submissionTarget!==void 0)return[];let t=this.pendingSubmissions.map(e=>e.requestId);if(t.length===0)return t;e.pendingSubmissions=[...e.pendingSubmissions,...this.pendingSubmissions];for(let n of t){let t=this.submissionSettlements.get(n);t!==void 0&&e.submissionSettlements.set(n,t);let r=this.inFlightPrompts.get(n);r!==void 0&&e.inFlightPrompts.set(n,r)}this.submissionSettlements.clear(),this.submissionTarget=e,e.promptAttempted||=this.promptAttempted;for(let{event:t}of e.eventSource.getSnapshot().entries)e.observeSubmissionEvent(t);return e.observeSubmissionInbox(),e.notifier.markDirty(),t}submissionOwner(){return this.submissionTarget?.submissionOwner()??this}get hasInFlightPrompts(){return this.inFlightPrompts.size>0}activeTurnForSteering(){let e=this.projections.get(np);return typeof e==`string`?e:null}async prompt(e,t,n,r){if(this.submissionTarget!==void 0)return this.submissionTarget.prompt(e,t,n,r);let i=r??Am();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=Im(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Im()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}let c=this.submissionOwner();return!s.ok&&s.error.code===`remote/outcome-unknown`&&c.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(c.acceptPrompt(),s):(r!==void 0&&c.retireFailedSubmission(r),c.promptError={op:`send`,error:s.error,requestId:i},c.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i);let e=this.submissionOwner();e.inFlightPrompts.get(i)===a&&e.inFlightPrompts.delete(i),this.notifier.markDirty()}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Jm})}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,...Ym}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}estimatedBytes(){let e=this.projections.revision;return this.cachedProjectionBytesRevision!==e&&(this.cachedProjectionBytes=wm(this.projections.values()),this.cachedProjectionBytesRevision=e),(this.eventSource.estimatedBytes>0?this.eventSource.estimatedBytes:Dm(this.cachedJournal))+this.assistantStream.estimatedPendingBytes()+this.toolOutputs.estimatedBytes+this.cachedProjectionBytes}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:new Map(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(rp),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Jm),e!==this.openGeneration||this.events!==n)return;this.cachedJournal=void 0,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:qm(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)),e.key===`subagent`&&this.address?.mode===`unknown`&&this.notifier.markDirty()}let t=this.lastSyncedAt;this.lastSyncedAt=Date.now(),(e.type!==`assistant-stream`||t===void 0)&&this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=m(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,rp),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);else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId);else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),t&&this.notifier.markDirty()}else e?.type===`transient`&&this.eventSource.append(e.entry)}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e);return}let n=this.hasMore;this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t),n!==t&&this.notifier.markDirty();for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:Qm(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=Qm(e.content),this.notifySubmissionObserved(i,i.admitted),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,Qm(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}notifySubmissionObserved(e,t){e.observed||(e.observed=!0,e.onObserved?.(t))}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,this.notifySubmissionObserved(n,t),Zm(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){if(this.submissionTarget!==void 0){this.submissionTarget.retireFailedSubmission(e);return}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){if(this.submissionTarget!==void 0){this.submissionTarget.finishSubmission(e,t);return}let n=this.submissionSettlements.get(e);
|
|
128
128
|
/* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
|
|
129
|
-
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 Wm(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function Gm(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 Km=class{views=/* @__PURE__ */ new Map;maxEntries;maxBytes;estimateBytes;cachedBytes=0;constructor(e={}){this.maxEntries=Math.max(0,e.maxEntries??8),this.maxBytes=Math.max(0,e.maxBytes??25165824),this.estimateBytes=e.estimateBytes??xm}get size(){return this.views.size}get totalBytes(){return this.cachedBytes}take(e){let t=this.views.get(e);if(t!==void 0)return this.views.delete(e),this.cachedBytes-=t.bytes,t.view}remember(e,t){let n=this.views.get(e);n!==void 0&&(this.views.delete(e),this.cachedBytes-=n.bytes);let r=Math.max(0,this.estimateBytes(t));if(this.maxEntries===0||r>this.maxBytes)return[e];this.views.set(e,{view:t,bytes:r}),this.cachedBytes+=r;let i=[];for(;this.views.size>this.maxEntries||this.cachedBytes>this.maxBytes;){let t=this.views.entries().next().value;if(t[0]===e)break;this.views.delete(t[0]),this.cachedBytes-=t[1].bytes,i.push(t[0])}return i}delete(e){let t=this.views.get(e);t!==void 0&&(this.views.delete(e),this.cachedBytes-=t.bytes)}clear(){this.views.clear(),this.cachedBytes=0}};function qm(e){return e===-1?-1:p(e)}let Jm=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]),Ym=/* @__PURE__ */ new Set([...Xf,`codexhostTurnTimes`,`codexhostUsage`,`contextPressure`,`contextBreakdown`,`inbox`,`queueState`,`turnOutline`,`sessionStats`,`compacting`,`goal`,`agentPreset`,`plan`,`todos`,`permissions`,`nativePermissions`,`modelSelection`,`attachmentInput`,`imageLimits`,`sentMessageEdit`]);var Xm=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new Km;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;workspaceOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;workspaceStartCursor;workspaceHistory=/* @__PURE__ */ new Map;activeWorkspacePage;activeListCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];projectionSnapshotCache=/* @__PURE__ */ new Map;projectionsBySessionCache={};notifier=new um(()=>{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)for(let t of this.recentViews.remember(e,r))this.projectionStores.get(t)?.discard(Xf);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.resetListQueries(),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 Um(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 fm(Ym);let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markFrameDirty()}),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.revision;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.revision===a&&r.clear():r.seed({...t.value,asOfSeq:qm(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.resetListQueries(),this.refreshList())}resetListQueries(){this.nextCursor=void 0,this.workspaceStartCursor=void 0,this.workspaceHistory=/* @__PURE__ */ new Map,this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null}hasSummary(e){return this.summaries.some(t=>t.sessionId===e)}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){if(e===void 0)return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve();let t=this.workspaceHistory,n=t.get(e);if(n?.pending)return n.pending;let r=n?n.cursor:this.workspaceStartCursor;if(!r||this.disposed)return Promise.resolve();let i={cursor:r,state:`loading`};return t.set(e,i),this.notifier.markDirty(),i.pending=(async()=>{t===this.workspaceHistory&&await this.refreshList(r,e)})().finally(()=>{delete i.pending,t===this.workspaceHistory&&this.notifier.markDirty()}),i.pending}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null){if(t===this.activeWorkspacePage&&e===this.activeListCursor)return this.listInflight;let n=this.workspaceHistory;return this.listInflight.catch(()=>void 0).then(()=>{if(n===this.workspaceHistory)return this.refreshList(e,t)})}let n=this.includeArchived;this.activeWorkspacePage=t,this.activeListCursor=e;let r=t===void 0?void 0:this.workspaceHistory.get(t);r||(this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0);let a=e=>{r?r.state=`retry`:(this.listState=`error`,this.listError=e)},o=this.summaries,s=[];return this.listMutations=s,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==s)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),a=new Set(i.value.items.map(e=>e.sessionId)),c=r!==void 0||i.value.nextCursor!==void 0,l=i.value.nextCursor??null;if(r){let e=new Set(this.summaries.map(e=>e.sessionId)),t=i.value.items.filter(t=>!t.blank&&!e.has(t.sessionId));for(let e of t)this.workspaceOnlyIds.add(e.sessionId);r.cursor=l,r.state=l?t.length>0?`search`:`continue`:`done`}else{for(let e of a)this.workspaceOnlyIds.delete(e);(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=l),e===void 0&&this.workspaceStartCursor==null&&(this.workspaceStartCursor=l)}let u=[...i.value.items,...o.filter(e=>!a.has(e.sessionId)&&(c||!n&&t.has(e.sessionId)))],d=this.listPhase===`pending`?u:Yp(o,u,e=>e.sessionId),f=/* @__PURE__ */ new Set;for(let e of s)e.kind===`remove`&&f.add(e.sessionId);for(let e of d)e.running&&!f.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let p=s.reduce(Zm,d);this.summaries=p;let m=new Set(p.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(a.has(e)||!m.has(e))&&this.summaryOnlyIds.delete(e);for(let e of this.workspaceOnlyIds)m.has(e)||this.workspaceOnlyIds.delete(e);let ee=this.retainedIds(p);for(let e of this.engagedSessions)this.pruneEngagement(e,ee);r||(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===s&&(this.headRefreshRevision+=1)}else a(i.error)}catch(e){if(this.listMutations!==s)return;if(r)r.state=`retry`;else if((0,i.isRemoteFailure)(e))a(e);else throw e}finally{this.listMutations===s&&(this.activeWorkspacePage=void 0,this.activeListCursor=void 0,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=Qm(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:Qm(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))&&this.notifier.markDirty(),n}mergeSummary(e){let t=this.recordMutation({kind:`upsert`,summary:e},`frame`);return this.updateParentAvailability(),t}recordMutation(e,t=`microtask`){if(this.disposed)return!1;this.listMutations?.push(e);let n=Zm(this.summaries,e);return n!==this.summaries&&(this.summaries=n,t===`frame`?this.notifier.markFrameDirty():this.notifier.markDirty(),!0)}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))&&!Ym.has(e.key)&&this.notifier.markFrameDirty()}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=qm(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,Xf)}this.notifier.markFrameDirty()}handleSessionAdded(e,t=!0){let n=t&&this.summaryOnlyIds.delete(e.sessionId),r=t&&this.workspaceOnlyIds.delete(e.sessionId),i=this.mergeSummary(e);(n||r)&&!i&&this.notifier.markFrameDirty(),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let a=this.sessions.get(e.sessionId);a?.handleRestored(),a?.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=qm(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:em(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){let t=this.summaryOnlyIds.delete(e),n=this.workspaceOnlyIds.delete(e),r=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`),i=this.recordMutation(r?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e},`frame`),a=!1;if(r){let t=this.sessions.get(e);a=t?.getSnapshot().running===!0,t?.handleRunning(!1)}else this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved();let o=this.projectionStores.get(e)?.values().subagentCatalog,s=!r&&(o===void 0||o.length===0)&&this.projectionStores.delete(e);this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e);let c=this.projectionLoads.delete(e);!i&&(t||n||s||c||a)&&this.notifier.markFrameDirty();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);let n=this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0},`frame`);this.updateParentAvailability();let r=this.sessions.get(e),i=r?.getSnapshot().running;r?.handleRunning(t),!n&&r!==void 0&&i!==t&&this.notifier.markFrameDirty()}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t},`frame`)}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(Jm);this.resetListQueries(),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=lm(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);e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e);let n=this.projectionSnapshotCache.size!==this.projectionStores.size;for(let[e,t]of this.projectionStores){let r=t.values(),i=this.projectionLoads.get(e),a=i?.state??`idle`,o=i?.error??null,s=this.projectionSnapshotCache.get(e);(s===void 0||s.values!==r||s.state!==a||s.error!==o)&&(this.projectionSnapshotCache.set(e,{values:r,state:a,error:o}),n=!0)}if(n){for(let e of this.projectionSnapshotCache.keys())this.projectionStores.has(e)||this.projectionSnapshotCache.delete(e);this.projectionsBySessionCache=Object.fromEntries(this.projectionSnapshotCache)}return{items:this.itemsCache,hasMore:!!this.nextCursor,canSearchWorkspaceHistory:!!this.workspaceStartCursor,workspaceHistory:Object.fromEntries([...this.workspaceHistory].map(([e,t])=>[e,t.pending?`loading`:t.state])),workspaceOnlyIds:[...this.workspaceOnlyIds],headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:this.projectionsBySessionCache}}};function Zm(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.findIndex(e=>e.sessionId===t.summary.sessionId);if(n===-1)return[t.summary,...e];let r=e[n],i={...r,blank:r.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...r.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...r.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...r.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};if(i.cwd===r.cwd&&i.parentSessionId===r.parentSessionId&&i.origin===r.origin&&i.blank===r.blank&&i.agentAvailable===r.agentAvailable&&i.running===r.running)return e;let a=[...e];return a[n]=i,a}case`remove`:return e.findIndex(e=>e.sessionId===t.sessionId)===-1?e:e.filter(e=>e.sessionId!==t.sessionId);case`status`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(r.running===t.running&&r.agentAvailable===t.agentAvailable&&(!t.running||!r.blank))return e;let i=[...e];return i[n]={...r,running:t.running,agentAvailable:t.agentAvailable,blank:r.blank&&!t.running},i}case`activity`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!(t.updatedAt>r.updatedAt))return e;let i=[...e];return i[n]={...r,updatedAt:t.updatedAt},i}case`engaged`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!r.blank)return e;let i=[...e];return i[n]={...r,blank:!1},i}}}function Qm(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var $m=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},eh=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 th(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 nh(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 rh(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let ih=Object.freeze({referenceCount:0,retainedBy:rh({})});async function ah(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 oh=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]);ah(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()}},sh=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;projectedItemCache=/* @__PURE__ */ new Map;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new Xm(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}}handoffSubmissions(e,t){let n=this.scopes.get(e)?.session;if(n===void 0||e===t||n.getSnapshot().pendingSubmissions.length===0&&!n.hasInFlightPrompts)return;let r=this.retain(t,{source:`controllerOperation`}),i=this.retain(e,{source:`controllerOperation`}),a=this.manager.get(t),o=new Set(n.handoffSubmissions(a)),s=[],c=!1,l=()=>{if(!c){c=!0;for(let e of s)e();r.release(),i.release()}},u=()=>{!n.hasInFlightPrompts&&!a.getSnapshot().pendingSubmissions.some(e=>o.has(e.requestId))&&l()};s.push(a.subscribe(u),n.subscribe(u)),r.ready.catch(l),i.ready.catch(l),u()}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}async loadSummary(e){await this.manager.loadSummary(e),this.closed||this.projectList()}syncSummary(e){return this.list.getSnapshot().byId[e]===void 0?this.closed||!this.manager.hasSummary(e)?!1:(this.projectList(),this.list.getSnapshot().byId[e]!==void 0):!0}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new $m(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 eh(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,nh(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}estimatedBytes(e){return this.scopes.get(e)?.session.estimatedBytes()??0}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:rh({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new oh(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?ih:Object.freeze({referenceCount:r,retainedBy:rh(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??ih}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:ih,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,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,state:c,error:l,errorPage:u,headRefreshRevision:d,summaryOnlyIds:f}=this.manager.getListSnapshot(),p=[],m={};for(let e of t){p.push(e.sessionId);let t=this.retentionSnapshot(e.sessionId).retainedBy,n=this.projectedItemCache.get(e.sessionId);if(n!==void 0&&n.entry===e&&n.retainedBy===t){m[e.sessionId]=n.summary;continue}let r={id:e.sessionId,displayTitle:th(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:t,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}};this.projectedItemCache.set(e.sessionId,{entry:e,retainedBy:t,summary:r}),m[e.sessionId]=r}if(this.projectedItemCache.size>t.length)for(let e of this.projectedItemCache.keys())m[e]===void 0&&this.projectedItemCache.delete(e);for(let e in r){let t=r[e]?.values.subagentCatalog;if(t!==void 0&&t.length!==0)for(let n of t){let t=n.id,r=m[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?m[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)&&(m[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}}for(let[t,n]of this.scopes){if(m[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;m[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:p,byId:m,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,loading:c===`loading`,listError:l?.message??null,listErrorPage:u,headRefreshRevision:d??0,summaryOnlyIds:f??[]})}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 ch=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function lh(e){let t=e.remote,n=e.get(`connection`),r=new sh(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=Om,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=$m,n.SessionEventStream=pe,n.SessionForkError=eh,n.apply=lh,n.createScope=_e,n.createSessionControlStream=fe,n.inject=ch,n.scopeOf=ve,t.exports}});
|
|
129
|
+
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 Zm(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function Qm(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 $m=class{views=/* @__PURE__ */ new Map;maxEntries;maxBytes;estimateBytes;cachedBytes=0;constructor(e={}){this.maxEntries=Math.max(0,e.maxEntries??8),this.maxBytes=Math.max(0,e.maxBytes??25165824),this.estimateBytes=e.estimateBytes??Om}get size(){return this.views.size}get totalBytes(){return this.cachedBytes}take(e){let t=this.views.get(e);if(t!==void 0)return this.views.delete(e),this.cachedBytes-=t.bytes,t.view}remember(e,t){let n=this.views.get(e);n!==void 0&&(this.views.delete(e),this.cachedBytes-=n.bytes);let r=Math.max(0,this.estimateBytes(t));if(this.maxEntries===0||r>this.maxBytes)return[e];this.views.set(e,{view:t,bytes:r}),this.cachedBytes+=r;let i=[];for(;this.views.size>this.maxEntries||this.cachedBytes>this.maxBytes;){let t=this.views.entries().next().value;if(t[0]===e)break;this.views.delete(t[0]),this.cachedBytes-=t[1].bytes,i.push(t[0])}return i}delete(e){let t=this.views.get(e);t!==void 0&&(this.views.delete(e),this.cachedBytes-=t.bytes)}clear(){this.views.clear(),this.cachedBytes=0}};function eh(e){return e===-1?-1:p(e)}let th=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]),nh=/* @__PURE__ */ new Set([...rp,`codexhostTurnTimes`,`codexhostUsage`,`contextPressure`,`contextBreakdown`,`inbox`,`queueState`,`turnOutline`,`sessionStats`,`compacting`,`goal`,`agentPreset`,`plan`,`todos`,`permissions`,`nativePermissions`,`modelSelection`,`attachmentInput`,`imageLimits`,`sentMessageEdit`]);var rh=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new $m;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;workspaceOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;workspaceStartCursor;workspaceHistory=/* @__PURE__ */ new Map;activeWorkspacePage;activeListCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];projectionSnapshotCache=/* @__PURE__ */ new Map;projectionsBySessionCache={};notifier=new _m(()=>{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)for(let t of this.recentViews.remember(e,r))this.projectionStores.get(t)?.discard(rp);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.resetListQueries(),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 Xm(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 ym(nh);let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markFrameDirty()}),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.revision;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.revision===a&&r.clear():r.seed({...t.value,asOfSeq:eh(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.resetListQueries(),this.refreshList())}resetListQueries(){this.nextCursor=void 0,this.workspaceStartCursor=void 0,this.workspaceHistory=/* @__PURE__ */ new Map,this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null}hasSummary(e){return this.summaries.some(t=>t.sessionId===e)}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){if(e===void 0)return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve();let t=this.workspaceHistory,n=t.get(e);if(n?.pending)return n.pending;let r=n?n.cursor:this.workspaceStartCursor;if(!r||this.disposed)return Promise.resolve();let i={cursor:r,state:`loading`};return t.set(e,i),this.notifier.markDirty(),i.pending=(async()=>{t===this.workspaceHistory&&await this.refreshList(r,e)})().finally(()=>{delete i.pending,t===this.workspaceHistory&&this.notifier.markDirty()}),i.pending}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null){if(t===this.activeWorkspacePage&&e===this.activeListCursor)return this.listInflight;let n=this.workspaceHistory;return this.listInflight.catch(()=>void 0).then(()=>{if(n===this.workspaceHistory)return this.refreshList(e,t)})}let n=this.includeArchived;this.activeWorkspacePage=t,this.activeListCursor=e;let r=t===void 0?void 0:this.workspaceHistory.get(t);r||(this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0);let a=e=>{r?r.state=`retry`:(this.listState=`error`,this.listError=e)},o=this.summaries,s=[];return this.listMutations=s,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==s)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),a=new Set(i.value.items.map(e=>e.sessionId)),c=r!==void 0||i.value.nextCursor!==void 0,l=i.value.nextCursor??null;if(r){let e=new Set(this.summaries.map(e=>e.sessionId)),t=i.value.items.filter(t=>!t.blank&&!e.has(t.sessionId));for(let e of t)this.workspaceOnlyIds.add(e.sessionId);r.cursor=l,r.state=l?t.length>0?`search`:`continue`:`done`}else{for(let e of a)this.workspaceOnlyIds.delete(e);(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=l),e===void 0&&this.workspaceStartCursor==null&&(this.workspaceStartCursor=l)}let u=[...i.value.items,...o.filter(e=>!a.has(e.sessionId)&&(c||!n&&t.has(e.sessionId)))],d=this.listPhase===`pending`?u:nm(o,u,e=>e.sessionId),f=/* @__PURE__ */ new Set;for(let e of s)e.kind===`remove`&&f.add(e.sessionId);for(let e of d)e.running&&!f.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let p=s.reduce(ih,d);this.summaries=p;let m=new Set(p.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(a.has(e)||!m.has(e))&&this.summaryOnlyIds.delete(e);for(let e of this.workspaceOnlyIds)m.has(e)||this.workspaceOnlyIds.delete(e);let ee=this.retainedIds(p);for(let e of this.engagedSessions)this.pruneEngagement(e,ee);r||(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===s&&(this.headRefreshRevision+=1)}else a(i.error)}catch(e){if(this.listMutations!==s)return;if(r)r.state=`retry`;else if((0,i.isRemoteFailure)(e))a(e);else throw e}finally{this.listMutations===s&&(this.activeWorkspacePage=void 0,this.activeListCursor=void 0,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=ah(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:ah(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))&&this.notifier.markDirty(),n}mergeSummary(e){let t=this.recordMutation({kind:`upsert`,summary:e},`frame`);return this.updateParentAvailability(),t}recordMutation(e,t=`microtask`){if(this.disposed)return!1;this.listMutations?.push(e);let n=ih(this.summaries,e);return n!==this.summaries&&(this.summaries=n,t===`frame`?this.notifier.markFrameDirty():this.notifier.markDirty(),!0)}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))&&!nh.has(e.key)&&this.notifier.markFrameDirty()}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=eh(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,rp)}this.notifier.markFrameDirty()}handleSessionAdded(e,t=!0){let n=t&&this.summaryOnlyIds.delete(e.sessionId),r=t&&this.workspaceOnlyIds.delete(e.sessionId),i=this.mergeSummary(e);(n||r)&&!i&&this.notifier.markFrameDirty(),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let a=this.sessions.get(e.sessionId);a?.handleRestored(),a?.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=eh(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:sm(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){let t=this.summaryOnlyIds.delete(e),n=this.workspaceOnlyIds.delete(e),r=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`),i=this.recordMutation(r?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e},`frame`),a=!1;if(r){let t=this.sessions.get(e);a=t?.getSnapshot().running===!0,t?.handleRunning(!1)}else this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved();let o=this.projectionStores.get(e)?.values().subagentCatalog,s=!r&&(o===void 0||o.length===0)&&this.projectionStores.delete(e);this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e);let c=this.projectionLoads.delete(e);!i&&(t||n||s||c||a)&&this.notifier.markFrameDirty();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);let n=this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0},`frame`);this.updateParentAvailability();let r=this.sessions.get(e),i=r?.getSnapshot().running;r?.handleRunning(t),!n&&r!==void 0&&i!==t&&this.notifier.markFrameDirty()}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t},`frame`)}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(th);this.resetListQueries(),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=gm(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);e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e);let n=this.projectionSnapshotCache.size!==this.projectionStores.size;for(let[e,t]of this.projectionStores){let r=t.values(),i=this.projectionLoads.get(e),a=i?.state??`idle`,o=i?.error??null,s=this.projectionSnapshotCache.get(e);(s===void 0||s.values!==r||s.state!==a||s.error!==o)&&(this.projectionSnapshotCache.set(e,{values:r,state:a,error:o}),n=!0)}if(n){for(let e of this.projectionSnapshotCache.keys())this.projectionStores.has(e)||this.projectionSnapshotCache.delete(e);this.projectionsBySessionCache=Object.fromEntries(this.projectionSnapshotCache)}return{items:this.itemsCache,hasMore:!!this.nextCursor,canSearchWorkspaceHistory:!!this.workspaceStartCursor,workspaceHistory:Object.fromEntries([...this.workspaceHistory].map(([e,t])=>[e,t.pending?`loading`:t.state])),workspaceOnlyIds:[...this.workspaceOnlyIds],headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:this.projectionsBySessionCache}}};function ih(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.findIndex(e=>e.sessionId===t.summary.sessionId);if(n===-1)return[t.summary,...e];let r=e[n],i={...r,blank:r.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...r.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...r.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...r.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};if(i.cwd===r.cwd&&i.parentSessionId===r.parentSessionId&&i.origin===r.origin&&i.blank===r.blank&&i.agentAvailable===r.agentAvailable&&i.running===r.running)return e;let a=[...e];return a[n]=i,a}case`remove`:return e.findIndex(e=>e.sessionId===t.sessionId)===-1?e:e.filter(e=>e.sessionId!==t.sessionId);case`status`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(r.running===t.running&&r.agentAvailable===t.agentAvailable&&(!t.running||!r.blank))return e;let i=[...e];return i[n]={...r,running:t.running,agentAvailable:t.agentAvailable,blank:r.blank&&!t.running},i}case`activity`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!(t.updatedAt>r.updatedAt))return e;let i=[...e];return i[n]={...r,updatedAt:t.updatedAt},i}case`engaged`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!r.blank)return e;let i=[...e];return i[n]={...r,blank:!1},i}}}function ah(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var oh=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},sh=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 ch(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 lh(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 uh(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let dh=Object.freeze({referenceCount:0,retainedBy:uh({})});async function fh(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 ph=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]);fh(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()}},mh=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;projectedItemCache=/* @__PURE__ */ new Map;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new rh(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}}handoffSubmissions(e,t){let n=this.scopes.get(e)?.session;if(n===void 0||e===t||n.getSnapshot().pendingSubmissions.length===0&&!n.hasInFlightPrompts)return;let r=this.retain(t,{source:`controllerOperation`}),i=this.retain(e,{source:`controllerOperation`}),a=this.manager.get(t),o=new Set(n.handoffSubmissions(a)),s=[],c=!1,l=()=>{if(!c){c=!0;for(let e of s)e();r.release(),i.release()}},u=()=>{!n.hasInFlightPrompts&&!a.getSnapshot().pendingSubmissions.some(e=>o.has(e.requestId))&&l()};s.push(a.subscribe(u),n.subscribe(u)),r.ready.catch(l),i.ready.catch(l),u()}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}async loadSummary(e){await this.manager.loadSummary(e),this.closed||this.projectList()}syncSummary(e){return this.list.getSnapshot().byId[e]===void 0?this.closed||!this.manager.hasSummary(e)?!1:(this.projectList(),this.list.getSnapshot().byId[e]!==void 0):!0}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new oh(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 sh(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,lh(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}estimatedBytes(e){return this.scopes.get(e)?.session.estimatedBytes()??0}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:uh({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new ph(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?dh:Object.freeze({referenceCount:r,retainedBy:uh(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??dh}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:dh,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,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,state:c,error:l,errorPage:u,headRefreshRevision:d,summaryOnlyIds:f}=this.manager.getListSnapshot(),p=[],m={};for(let e of t){p.push(e.sessionId);let t=this.retentionSnapshot(e.sessionId).retainedBy,n=this.projectedItemCache.get(e.sessionId);if(n!==void 0&&n.entry===e&&n.retainedBy===t){m[e.sessionId]=n.summary;continue}let r={id:e.sessionId,displayTitle:ch(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:t,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}};this.projectedItemCache.set(e.sessionId,{entry:e,retainedBy:t,summary:r}),m[e.sessionId]=r}if(this.projectedItemCache.size>t.length)for(let e of this.projectedItemCache.keys())m[e]===void 0&&this.projectedItemCache.delete(e);for(let e in r){let t=r[e]?.values.subagentCatalog;if(t!==void 0&&t.length!==0)for(let n of t){let t=n.id,r=m[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?m[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)&&(m[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}}for(let[t,n]of this.scopes){if(m[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;m[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:p,byId:m,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,loading:c===`loading`,listError:l?.message??null,listErrorPage:u,headRefreshRevision:d??0,summaryOnlyIds:f??[]})}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 hh=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function gh(e){let t=e.remote,n=e.get(`connection`),r=new mh(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=Fm,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=oh,n.SessionEventStream=pe,n.SessionForkError=sh,n.apply=gh,n.createScope=_e,n.createSessionControlStream=fe,n.inject=hh,n.scopeOf=ve,t.exports}});
|