@codexhost/cli-win32-arm64 0.26.1 → 0.27.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.
Files changed (58) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +561 -322
  4. package/app/console-web.js +543 -369
  5. package/app/desktop-controller.mjs +385 -243
  6. package/app/host-runtime.mjs +7774 -3488
  7. package/app/plugins/antigravity/plugin.mjs +8669 -417
  8. package/app/plugins/claude-code/plugin.mjs +736 -393
  9. package/app/plugins/codebuddy/plugin.mjs +388 -233
  10. package/app/plugins/codex-usage/plugin.mjs +363 -230
  11. package/app/plugins/copilot/plugin.mjs +388 -233
  12. package/app/plugins/cursor-cli/plugin.mjs +363 -230
  13. package/app/plugins/deepseek-harness/plugin.mjs +388 -233
  14. package/app/plugins/devin/plugin.mjs +363 -230
  15. package/app/plugins/grok/plugin.mjs +363 -230
  16. package/app/plugins/hermes/plugin.mjs +363 -230
  17. package/app/plugins/kimi-code/plugin.mjs +492 -270
  18. package/app/plugins/kiro-cli/plugin.mjs +363 -230
  19. package/app/plugins/omp/plugin.mjs +363 -230
  20. package/app/plugins/opencode/manifest.json +1 -1
  21. package/app/plugins/opencode/plugin.mjs +439 -248
  22. package/app/plugins/pi/plugin.mjs +363 -230
  23. package/app/plugins/qoder/plugin.mjs +363 -230
  24. package/app/plugins/qoder-cn/plugin.mjs +363 -230
  25. package/app/plugins/qwen-code/plugin.mjs +363 -230
  26. package/app/plugins/workbuddy/plugin.mjs +383 -245
  27. package/app/plugins/zcode/plugin.mjs +363 -230
  28. package/app/renderer-extension.js +2071 -555
  29. package/app/web/assets/index-D9l7_ThH.js +199 -0
  30. package/app/web/assets/index-nw2RXcDu.css +1 -0
  31. package/app/web/codexhost-settings.js +67 -67
  32. package/app/web/index.html +2 -2
  33. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  34. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +8 -8
  35. package/app/web/plugins/deepseek-ai__dsh-client-shortcuts/client.js +2 -2
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-approval/client.js +4 -1
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +75 -75
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +16 -16
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +19 -19
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +1 -1
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +2 -2
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-shortcuts/client.js +1 -1
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +2 -2
  46. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +18 -18
  47. package/app/web/plugins/deepseek-ai__dsh-client-ui-user-questions/client.js +4 -4
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +71 -71
  49. package/app/web/plugins.json +2 -1
  50. package/app/web-modules/server.mjs +2884 -1128
  51. package/bin/codexhost.exe +0 -0
  52. package/libexec/codexhost-node-repl.exe +0 -0
  53. package/libexec/codexhost-shell.exe +0 -0
  54. package/libexec/codexhost-shim.exe +0 -0
  55. package/libexec/codexhost-updater.exe +0 -0
  56. package/package.json +1 -1
  57. package/app/web/assets/index-CR4Y8Ndj.css +0 -1
  58. package/app/web/assets/index-Dw-yHAxN.js +0 -196
@@ -110,20 +110,20 @@ function ho(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}//
110
110
  function go(e,t){let n=/* @__PURE__ */ _o(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 _o(e,t){let n=new S({check:`custom`,...g(t)});return n._zod.check=e,n}function vo(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 yo(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??da,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 bo(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 T(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),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,T(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&vo(o.schema,c),t.io===`input`&&E(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function xo(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function So(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}/${xo(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+xo(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 Co(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;Co(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 wo=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),To=[`oneOf`,`anyOf`];function Eo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Do(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!wo.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]??Eo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ae(n,r,e.length===1?e[0]:Do(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=Eo(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 Oo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of wo)if(t in e)return;let n=t.filter(e=>To.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Do(t);else{let e=n[0],i=To.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=>Do([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,vo(e,r))}function ko(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)):vo(i,s),vo(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())Co(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)??[])Oo(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)}vo(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:jo(t,`input`,e.processors),output:jo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function E(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return E(r.element,n);if(r.type===`set`)return E(r.valueType,n);if(r.type===`lazy`)return E(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return E(r.innerType,n);if(r.type===`intersection`)return E(r.left,n)||E(r.right,n);if(r.type===`record`||r.type===`map`)return E(r.keyType,n)||E(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:E(r.in,n)||E(r.out,n);if(r.type===`object`){for(let e in r.shape)if(E(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(E(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(E(e,n))return!0;return!!(r.rest&&E(r.rest,n))}return!1}let Ao=(e,t={})=>n=>{let r=yo({...n,processors:t});return T(e,r),So(r,e),ko(r,e)},jo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=yo({...i??{},target:a,io:t,processors:n});return T(e,o),So(o,e),ko(o,e)},Mo=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},No=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Po=(e,t)=>{Mo(e,`minimum`,t),No(e,`maximum`,t)},Fo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Io=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Lo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Ro=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},zo=(e,t)=>Mo(e,`minimum`,t.minimum),Bo=(e,t)=>No(e,`maximum`,t.maximum),Vo=e=>(t,n)=>{Ro(t,n.format);let[r,i]=e[n.format];Mo(t,`minimum`,r),No(t,`maximum`,i)},Ho={greater_than:(e,t)=>Mo(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>No(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Fo(e,t.value),number_format:Vo(Ye),bigint_format:Vo(Xe),min_length:zo,max_length:Bo,length_equals:(e,t)=>Po(e,t.length),min_size:zo,max_size:Bo,size_equals:(e,t)=>Po(e,t.size),string_format:(e,t)=>{Ro(e,t.format),t.pattern&&Io(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)=>Lo(e,t.mime)};function D(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Ho[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Mo(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Mo(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&No(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&No(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Fo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Lo(t,i.mime);for(let e of i.patterns??[])Io(t,e);return t}let Uo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Wo=/* @__PURE__ */ new Map([[Ur,Dn],[Gr,On]]),Go=e=>Wo.get(e)??e,Ko=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=D(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Uo[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(Go);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}))])}},qo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=D(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)):bo(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}))])}},Jo=(e,t,n,r)=>{n.type=`boolean`},Yo=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Xo=(e,t,n,r)=>{n.not={}},Zo=(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)},Qo=(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(bo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(bo(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}},$o=(e,t,n,r)=>{bo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},es=(e,t,n,r)=>{bo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ts=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=D(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=T(a.element,t,{...r,path:[...r.path,`items`]})};function ns(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?ns(t.out):t.type===`catch`?ns(t.innerType):e._zod.optin}let rs=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&bo(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,T(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`?ns(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=T(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},is=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>T(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},as=(e,t,n,r)=>{let i=e._zod.def,a=T(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=T(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},os=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>T(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?T(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?ns(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}=D(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function ss(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=ss(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=>ss(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`)?zn:Rn).source)),p}let cs=/* @__PURE__ */ new WeakMap;function ls(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 cs.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=ss(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 us=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=D(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=T(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ae(i.patternProperties,Go(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=T(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=cs.get(t);n||(n=[],cs.set(t,n),t.deferred.push(()=>ls(t))),n.push(e)}i.additionalProperties=T(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&ns(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))}},ds=(e,t,n,r)=>{let i=e._zod.def,a=T(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},fs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ps=Symbol();function ms(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(bo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),ps):JSON.parse(o)}let hs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=ms(i.defaultValue,e,t,n,r);o!==ps&&(n.default=o)},gs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=ms(i.defaultValue,e,t,n,r);o!==ps&&(n._prefault=o)},_s=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{bo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},vs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;T(o,t,r);let s=t.seen.get(e);s.ref=o},ys=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},bs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},xs=(e,t,n,r)=>{let i=e._zod.innerType;T(i,t,r);let a=t.seen.get(e);a.ref=i},Ss=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function Cs(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 O=/*@__PURE__*/ y(`ZodError`,(e,t)=>{Vt.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Ss.has(n)||(Ss.add(n),Cs(n,`format`,e=>t=>Wt(e,t)),Cs(n,`flatten`,e=>t=>Ut(e,t)),Cs(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),Cs(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}),ws=/* @__PURE__ */ Kt(O),Ts=/* @__PURE__ */ qt(O),Es=/* @__PURE__ */ Jt(O),Ds=/* @__PURE__ */ Xt(O),Os=/* @__PURE__ */ nn(O),ks=/* @__PURE__ */ rn(O),As=/* @__PURE__ */ an(O),js=/* @__PURE__ */ on(O),Ms=/* @__PURE__ */ sn(O),Ns=/* @__PURE__ */ cn(O),Ps=/* @__PURE__ */ ln(O),Fs=/* @__PURE__ */ un(O);function Is(){b.localeError||x(sa())}function Ls(){b.memoizer||x({memoizer:ia()})}let k=/*@__PURE__*/ y(`ZodType`,(e,t)=>(Is(),C.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(tl(e,t))},superRefine(e,t){return this.check(nl(e,t))},overwrite(e){return this.check(/* @__PURE__ */ oo(e))},optional(){return Pc(this)},exactOptional(){return Ic(this)},nullable(){return Rc(this)},nullish(){return Pc(Rc(this))},nonoptional(e){return Wc(this,e)},array(){return F(this)},or(e){return R([this,e])},and(e){return Tc(this,e)},transform(e){return Jc(this,Mc(e))},default(e){return Bc(this,e)},prefault(e){return Hc(this,e)},catch(e){return Kc(this,e)},pipe(e){return Jc(this,e)},readonly(){return Xc(this)},describe(e){let t=this.clone();return da.add(t,{description:e}),t},meta(...e){if(e.length===0)return da.get(this);let t=this.clone();return da.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`,{...dr(this),jsonSchema:{input:jo(this,`input`),output:jo(this,`output`)}})},set"~standard"(e){vt(this,`~standard`,e)},parse:function e(t,n){return ws(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ts(this,t,n,{callee:e})},safeParse(e,t){return Es(this,e,t)},async safeParseAsync(e,t){return Ds(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){vt(this,`spa`,e)},validate(e,t){return $t(this,e,t)},validateAsync(e,t){return tn(this,e,t)},encode:function e(t,n){return Os(this,t,n,{callee:e})},decode:function e(t,n){return ks(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await As(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await js(this,t,n,{callee:e})},safeEncode(e,t){return Ms(this,e,t)},safeDecode(e,t){return Ns(this,e,t)},async safeEncodeAsync(e,t){return Ps(this,e,t)},async safeDecodeAsync(e,t){return Fs(this,e,t)},toJSONSchema(e){return Ao(this,{})(e)},get description(){return da.get(this)?.description},get _def(){return this._zod.def}}),Rs=/*@__PURE__*/ y(`_ZodString`,(e,t)=>{fr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ko(e,t,n,r)},/*@__PURE__*/ bt({format:e=>D(e).format??null,minLength:e=>D(e).minimum??null,maxLength:e=>D(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ eo(...e))},includes(...e){return this.check(/* @__PURE__ */ ro(...e))},startsWith(...e){return this.check(/* @__PURE__ */ io(...e))},endsWith(...e){return this.check(/* @__PURE__ */ ao(...e))},min(...e){return this.check(/* @__PURE__ */ Qa(...e))},max(...e){return this.check(/* @__PURE__ */ Za(...e))},length(...e){return this.check(/* @__PURE__ */ $a(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Qa(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ to(e))},uppercase(e){return this.check(/* @__PURE__ */ no(e))},trim(){return this.check(/* @__PURE__ */ co())},normalize(...e){return this.check(/* @__PURE__ */ so(...e))},toLowerCase(){return this.check(/* @__PURE__ */ lo())},toUpperCase(){return this.check(/* @__PURE__ */ uo())},slugify(){return this.check(/* @__PURE__ */ fo())}})),zs=/*@__PURE__*/ y(`ZodString`,(e,t)=>{fr.init(e,t),Rs.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ma(Ws,e))},url(e){return this.check(/* @__PURE__ */ ba(Js,e))},jwt(e){return this.check(/* @__PURE__ */ Fa(uc,e))},emoji(e){return this.check(/* @__PURE__ */ xa(Xs,e))},guid(e){return this.check(/* @__PURE__ */ ha(Gs,e))},uuid(e){return this.check(/* @__PURE__ */ ga(Ks,e))},uuidv4(e){return this.check(/* @__PURE__ */ _a(Ks,e))},uuidv6(e){return this.check(/* @__PURE__ */ va(Ks,e))},uuidv7(e){return this.check(/* @__PURE__ */ ya(Ks,e))},nanoid(e){return this.check(/* @__PURE__ */ Sa(Zs,e))},cuid(e){return this.check(/* @__PURE__ */ Ca(Qs,e))},cuid2(e){return this.check(/* @__PURE__ */ wa($s,e))},ulid(e){return this.check(/* @__PURE__ */ Ta(ec,e))},base64(e){return this.check(/* @__PURE__ */ Ma(sc,e))},base64url(e){return this.check(/* @__PURE__ */ Na(cc,e))},xid(e){return this.check(/* @__PURE__ */ Ea(tc,e))},ksuid(e){return this.check(/* @__PURE__ */ Da(nc,e))},ipv4(e){return this.check(/* @__PURE__ */ Oa(rc,e))},ipv6(e){return this.check(/* @__PURE__ */ ka(ic,e))},cidrv4(e){return this.check(/* @__PURE__ */ Aa(ac,e))},cidrv6(e){return this.check(/* @__PURE__ */ ja(oc,e))},e164(e){return this.check(/* @__PURE__ */ Pa(lc,e))},datetime(e){return this.check(/* @__PURE__ */ Ia(Bs,e))},date(e){return this.check(/* @__PURE__ */ La(Vs,e))},time(e){return this.check(/* @__PURE__ */ Ra(Hs,e))},duration(e){return this.check(/* @__PURE__ */ za(Us,e))}});function A(e){return/* @__PURE__ */ pa(zs,e)}let j=/*@__PURE__*/ y(`ZodStringFormat`,(e,t)=>{w.init(e,t),Rs.init(e,t)}),Bs=/*@__PURE__*/ y(`ZodISODateTime`,(e,t)=>{jr.init(e,t),j.init(e,t)}),Vs=/*@__PURE__*/ y(`ZodISODate`,(e,t)=>{Mr.init(e,t),j.init(e,t)}),Hs=/*@__PURE__*/ y(`ZodISOTime`,(e,t)=>{Nr.init(e,t),j.init(e,t)}),Us=/*@__PURE__*/ y(`ZodISODuration`,(e,t)=>{Pr.init(e,t),j.init(e,t)}),Ws=/*@__PURE__*/ y(`ZodEmail`,(e,t)=>{hr.init(e,t),j.init(e,t)}),Gs=/*@__PURE__*/ y(`ZodGUID`,(e,t)=>{pr.init(e,t),j.init(e,t)}),Ks=/*@__PURE__*/ y(`ZodUUID`,(e,t)=>{mr.init(e,t),j.init(e,t)});function qs(e){return/* @__PURE__ */ ga(Ks,e)}let Js=/*@__PURE__*/ y(`ZodURL`,(e,t)=>{Cr.init(e,t),j.init(e,t)});function Ys(e){return/* @__PURE__ */ ba(Js,e)}let Xs=/*@__PURE__*/ y(`ZodEmoji`,(e,t)=>{wr.init(e,t),j.init(e,t)}),Zs=/*@__PURE__*/ y(`ZodNanoID`,(e,t)=>{Tr.init(e,t),j.init(e,t)}),Qs=/*@__PURE__*/ y(`ZodCUID`,(e,t)=>{Er.init(e,t),j.init(e,t)}),$s=/*@__PURE__*/ y(`ZodCUID2`,(e,t)=>{Dr.init(e,t),j.init(e,t)}),ec=/*@__PURE__*/ y(`ZodULID`,(e,t)=>{Or.init(e,t),j.init(e,t)}),tc=/*@__PURE__*/ y(`ZodXID`,(e,t)=>{kr.init(e,t),j.init(e,t)}),nc=/*@__PURE__*/ y(`ZodKSUID`,(e,t)=>{Ar.init(e,t),j.init(e,t)}),rc=/*@__PURE__*/ y(`ZodIPv4`,(e,t)=>{Fr.init(e,t),j.init(e,t)}),ic=/*@__PURE__*/ y(`ZodIPv6`,(e,t)=>{Rr.init(e,t),j.init(e,t)}),ac=/*@__PURE__*/ y(`ZodCIDRv4`,(e,t)=>{zr.init(e,t),j.init(e,t)}),oc=/*@__PURE__*/ y(`ZodCIDRv6`,(e,t)=>{Vr.init(e,t),j.init(e,t)}),sc=/*@__PURE__*/ y(`ZodBase64`,(e,t)=>{Wr.init(e,t),j.init(e,t)}),cc=/*@__PURE__*/ y(`ZodBase64URL`,(e,t)=>{qr.init(e,t),j.init(e,t)}),lc=/*@__PURE__*/ y(`ZodE164`,(e,t)=>{Jr.init(e,t),j.init(e,t)}),uc=/*@__PURE__*/ y(`ZodJWT`,(e,t)=>{Xr.init(e,t),j.init(e,t)}),dc=/*@__PURE__*/ y(`ZodNumber`,(e,t)=>{Zr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ bt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=D(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=D(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=D(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>D(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},min(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Ka(e,t))},lte(e,t){return this.check(/* @__PURE__ */ qa(e,t))},max(e,t){return this.check(/* @__PURE__ */ qa(e,t))},int(e){return this.check(N(e))},safe(e){return this.check(N(e))},positive(e){return this.check(/* @__PURE__ */ Ja(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Ya(0,e))},negative(e){return this.check(/* @__PURE__ */ Ka(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ qa(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},step(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},finite(){return this}}));function M(e){return/* @__PURE__ */ Ba(dc,e)}let fc=/*@__PURE__*/ y(`ZodNumberFormat`,(e,t)=>{Qr.init(e,t),dc.init(e,t)});function N(e){return/* @__PURE__ */ Va(fc,e)}let pc=/*@__PURE__*/ y(`ZodBoolean`,(e,t)=>{$r.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jo(e,t,n,r)});function P(e){return/* @__PURE__ */ Ha(pc,e)}let mc=/*@__PURE__*/ y(`ZodNull`,(e,t)=>{ei.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r)});function hc(e){return/* @__PURE__ */ Ua(mc,e)}let gc=/*@__PURE__*/ y(`ZodUnknown`,(e,t)=>{ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function _c(){return/* @__PURE__ */ Wa(gc)}let vc=/*@__PURE__*/ y(`ZodNever`,(e,t)=>{ni.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r)});function yc(e){return/* @__PURE__ */ Ga(vc,e)}let bc=/*@__PURE__*/ y(`ZodArray`,(e,t)=>{Ls(),oi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ Qa(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Qa(1,e))},max(e,t){return this.check(/* @__PURE__ */ Za(e,t))},length(e,t){return this.check(/* @__PURE__ */ $a(e,t))},unwrap(){return this.element}});function F(e,t){return/* @__PURE__ */ po(bc,e,t)}let xc=/*@__PURE__*/ y(`ZodObject`,(e,t)=>{Ls(),fi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),Et(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return V(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:_c()}))},loose(){return this.clone(h(this._zod.def,{catchall:_c()}))},strict(){return this.clone(h(this._zod.def,{catchall:yc()}))},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(Nc,this,e[0])},exactPartial(...e){return it(Fc,this,e[0],`exactPartial`)},required(...e){return at(Uc,this,e[0])}});function I(e,t){let n={type:`object`,shape:e??{},...g(t)};return new xc(n)}function L(e,t){return new xc({type:`object`,shape:e,catchall:yc(),...g(t)})}let Sc=/*@__PURE__*/ y(`ZodUnion`,(e,t)=>{mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.options=t.options});function R(e,t){return new Sc({type:`union`,options:e,...g(t)})}let Cc=/*@__PURE__*/ y(`ZodDiscriminatedUnion`,(e,t)=>{Sc.init(e,t),gi.init(e,t)});function z(e,t,n){return new Cc({type:`union`,options:t,discriminator:e,...g(n)})}let wc=/*@__PURE__*/ y(`ZodIntersection`,(e,t)=>{_i.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r)});function Tc(e,t){return new wc({type:`intersection`,left:e,right:t})}let Ec=/*@__PURE__*/ y(`ZodTuple`,(e,t)=>{Ls(),bi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(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 Nc({type:`optional`,innerType:e}))})}});function Dc(e,t,n){let r=t instanceof C;return new Ec({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let Oc=/*@__PURE__*/ y(`ZodRecord`,(e,t)=>{Ls(),wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>us(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function B(e,t,n){return!t||!t._zod?new Oc({type:`record`,keyType:A(),valueType:e,...g(t)}):new Oc({type:`record`,keyType:e,valueType:t,...g(n)})}let kc=/*@__PURE__*/ y(`ZodEnum`,(e,t)=>{Ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(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 kc({...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 kc({...t,checks:[],...g(r),entries:i})}});function V(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new kc({type:`enum`,entries:n,...g(t)})}let Ac=/*@__PURE__*/ y(`ZodLiteral`,(e,t)=>{Ei.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(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 H(e,t){return new Ac({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let jc=/*@__PURE__*/ y(`ZodTransform`,(e,t)=>{Ls(),Di.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(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 Mc(e){return new jc({type:`transform`,transform:e})}let Nc=/*@__PURE__*/ y(`ZodOptional`,(e,t)=>{ki.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e){return new Nc({type:`optional`,innerType:e})}let Fc=/*@__PURE__*/ y(`ZodExactOptional`,(e,t)=>{Ai.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e){return new Fc({type:`optional`,innerType:e})}let Lc=/*@__PURE__*/ y(`ZodNullable`,(e,t)=>{ji.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rc(e){return new Lc({type:`nullable`,innerType:e})}let zc=/*@__PURE__*/ y(`ZodDefault`,(e,t)=>{Mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bc(e,t){return new zc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Vc=/*@__PURE__*/ y(`ZodPrefault`,(e,t)=>{Pi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e,t){return new Vc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Uc=/*@__PURE__*/ y(`ZodNonOptional`,(e,t)=>{Fi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wc(e,t){return new Uc({type:`nonoptional`,innerType:e,...g(t)})}let Gc=/*@__PURE__*/ y(`ZodCatch`,(e,t)=>{Ri.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Kc(e,t){return new Gc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Dt(t)})}let qc=/*@__PURE__*/ y(`ZodPipe`,(e,t)=>{zi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.in=t.in,e.out=t.out});function Jc(e,t){return new qc({type:`pipe`,in:e,out:t})}let Yc=/*@__PURE__*/ y(`ZodReadonly`,(e,t)=>{Vi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xc(e){return new Yc({type:`readonly`,innerType:e})}let Zc=/*@__PURE__*/ y(`ZodLazy`,(e,t)=>{Ui.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Qc(e){return new Zc({type:`lazy`,getter:e})}let $c=/*@__PURE__*/ y(`ZodCustom`,(e,t)=>{Wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(e,t,n,r)});function el(e,t){return/* @__PURE__ */ mo($c,e??(()=>!0),t)}function tl(e,t={}){return/* @__PURE__ */ ho($c,e,t)}function nl(e,t){return/* @__PURE__ */ go(e,t)}function rl(e){return/* @__PURE__ */ Ia(Bs,e)}function il(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 al=R([A(),M(),P(),hc()]);function ol(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 sl=el(ol,{message:`JSON value must not contain circular references`}),cl=Qc(()=>R([al,F(cl),B(A(),cl)])),U=sl.pipe(cl);sl.pipe(F(cl));let ll=sl.pipe(B(A(),cl)),ul=L({code:A().min(1),message:A().min(1),retryable:P(),diagnostic:A().min(1).optional(),stage:A().min(1).optional(),durationMs:M().int().nonnegative().optional(),stderrTail:A().min(1).optional()}).superRefine(il([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),dl=A().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),fl=e=>A().min(1).max(e).refine(e=>e.trim().length>0),pl=B(dl,I({label:fl(256).optional(),description:fl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),ml=B(dl,fl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),hl=A().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),W=hl.brand(),G=hl.brand(),gl=hl.brand();hl.brand(),hl.brand();let _l=A().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),vl=_l.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),yl=I({modes:F(I({id:vl,label:_l.max(256),description:_l.max(1024).optional(),dangerous:P().optional(),localizations:pl.optional()}).strict()).min(1).max(32),defaultModeId:vl}).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`]})});I({threadId:G,permissionModeId:vl}).strict();let K=M().int().safe().nonnegative(),bl=M().finite().nonnegative(),xl=M().finite().min(0).max(100),Sl=I({version:R([H(3),H(4)]).optional(),requestId:A().min(1),turnId:A().min(1).max(1024),outputTokens:K,startedAtMs:K,completedAtMs:K}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Cl=I({version:R([H(2),H(3),H(4)]).optional(),value:bl,turnId:A().min(1).max(1024),at:K}).strict();I({outputTimings:F(Sl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Cl.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Cl.extend({value:K}).optional()}).strict();let wl=e=>ml.refine(t=>Object.values(t).every(t=>t.length<=e)),Tl=I({composerIndicators:F(I({kind:H(`countdown`),id:A().min(1).max(64),expiresAtUnix:K,label:wl(256).optional(),tooltip:wl(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:K.optional(),cachedInputTokens:K.optional(),cacheWriteInputTokens:K.optional(),outputTokens:K.optional(),outputTokensPerSecond:bl.optional(),sessionOutputTokensPerSecond:bl.optional(),apiOutputTokensPerSecond:bl.optional(),reasoningOutputTokens:K.optional(),totalTokens:K.optional(),totalCostUsd:bl.optional(),totalCredits:bl.optional(),contextUsagePercent:bl.optional(),cacheHitRatePercent:xl.optional(),contextWindowTokens:K.optional(),contextUsedTokens:K.optional(),planFiveHourUsedPercent:xl.optional(),planFiveHourResetsAtUnix:K.optional(),planSevenDayUsedPercent:xl.optional(),planSevenDayResetsAtUnix:K.optional(),sessionCacheHitRatePercent:xl.optional(),timeToFirstOutputMs:K.optional(),latestRequestTimeToFirstOutputMs:K.optional(),costSource:V([`publicPrice`,`native`]).optional(),unpricedModels:F(A().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`]})}),El=M().finite().min(0).max(100),Dl=V([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),Ol=I({id:A().min(1).max(256),label:A().min(1).max(256),localizations:pl.optional()}).strict(),kl=I({product:A().min(1),periodType:Dl.optional(),scope:Ol.optional(),localizations:pl.optional(),used:M().finite().nonnegative().optional(),limit:M().finite().nonnegative().optional(),unit:A().min(1).max(32).optional(),usagePercent:El,resetsAt:A().min(1).optional()}).strict(),Al=I({availableCount:M().int().safe().positive(),nextExpiresAt:A().min(1).optional(),expiresAt:F(A().min(1)).min(1).max(32).optional()}).strict(),jl=I({used:M().finite().nonnegative().optional(),limit:M().finite().nonnegative().optional(),unit:A().min(1).max(32).optional(),label:A().min(1).optional(),scope:Ol.optional(),localizations:pl.optional(),usedPercent:El,resetsAt:A().min(1).optional(),periodType:Dl,productUsage:F(kl).min(1).optional(),resetCredits:Al.optional()}).strict(),Ml=I({amount:M().finite().nonnegative(),currency:A().trim().min(1).max(8),label:A().trim().min(1).max(128).optional()}).strict();I({threadId:G,refresh:H(`exact`).optional()}).strict(),I({threadId:G,usage:Tl.nullable(),accountCredits:jl.optional(),accountBalance:Ml.optional(),accountCreditsSupported:P().optional()}).strict();let Nl=A().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Pl=A().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Fl=V([`priority`,`ultrafast`]),q=I({id:Pl,serviceTier:Fl.optional()}).strict();function Il(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let J=Nl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Ll=Nl.max(256),Rl=I({id:J,label:Nl.max(256)}).strict(),zl=I({ref:q,label:Nl.max(256),resolvedModelLabel:Ll.optional(),fastModel:q.optional(),supportedThinkingOptionIds:F(J).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 Bl(e,t){if(t)return e?.models.find(e=>Il(e.ref,t)||Il(e.fastModel,t))}let Vl=F(Rl).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)}),Hl=I({models:F(zl),defaultModel:q.optional(),thinkingOptions:Vl,defaultThinkingOptionId:J.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=>Il(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=>Il(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&&!Bl(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`]})}),Ul=I({fork:P(),forkAcrossCwd:P(),rollbackLastTurn:P()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Wl=V([`live`,`atCreate`]),Gl=I({configuration:I({selectModel:P(),selectThinkingOption:P(),selectPermissionMode:P(),permissionModeScope:Wl.default(`live`)}).strict(),history:Ul,subagents:I({observe:P(),readTranscript:P()}).strict().optional(),autonomousTurns:I({observe:P()}).strict().optional(),steer:P().optional(),persistentPlan:P().optional()}).strict();I({effectiveModel:q.optional(),resolvedModelLabel:Ll.optional(),effectiveThinkingOptionId:J.optional(),availableThinkingOptions:Vl.optional(),effectivePermissionModeId:vl.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 Kl=I({open:H(!0)}).strict();R([I({status:H(`ready`),catalog:Hl,permissionModes:yl.optional(),capabilities:Gl,webUi:Kl.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`]})}),I({status:V([`notInstalled`,`unavailable`,`error`]),error:ul}).strict()]),I({harnessId:W,cwd:Nl.max(16384).optional(),refresh:P().optional(),purpose:H(`availability`).optional(),credentialAccess:V([`allow`,`retry`]).optional()}).strict(),I({harnessId:W}).strict(),I({}).strict(),I({threadId:G,model:q}).strict(),I({threadId:G,thinkingOptionId:J}).strict(),I({threadId:G,includeReferenceCapability:P().optional()}).strict(),z(`owner`,[I({owner:H(`codex`),locked:P(),effectiveModel:q.optional(),resolvedModelLabel:Ll.optional(),effectiveThinkingOptionId:J.optional(),effectivePermissionModeId:vl.optional(),history:Ul.optional(),supportsThreadReferences:H(!0).optional()}).strict(),I({owner:H(`external`),harnessId:Nl.max(256),transportModelId:Nl.max(8192),effectiveModel:q.optional(),resolvedModelLabel:Ll.optional(),effectiveThinkingOptionId:J.optional(),availableThinkingOptions:Vl.optional(),effectivePermissionModeId:vl.optional(),catalog:Hl.optional(),history:Ul,usage:Tl.optional(),locked:H(!0)}).strict()]),I({threadIds:F(G).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 ql=z(`owner`,[I({threadId:G,owner:H(`codex`)}).strict(),I({threadId:G,owner:H(`external`),harnessId:A().max(256).pipe(W)}).strict()]);I({threads:F(ql).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)}),I({threadId:G,text:A().optional()}).strict(),I({kind:H(`application`),value:A().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),kt}}).pipe(I({expectedTurnId:gl,clientUserMessageId:A().min(1),delivery:V([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),V([`activeTurn`,`newTurn`]),I({delivery:V([`official`,`activeTurn`,`newTurn`])}).strict();let Jl=A().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),Yl=Jl.pipe(W),Xl=Yl.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Zl=A().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`),Ql=Ys().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),$l=I({en:A().max(4096),"zh-CN":A().max(4096).optional()}).strict(),eu=I({commands:F(I({terminal:A().max(256),command:A().max(4096)}).strict()).max(8),before:$l.optional(),after:$l.optional(),downloads:F(I({label:A().max(128),url:Ql}).strict()).max(8).optional()}).strict(),tu={id:Yl,name:A().trim().min(1).max(128),version:A().min(1).max(128),kind:H(`usage`).optional(),iconStyle:I({vector:I({viewBox:A().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:A().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:F(I({d:A().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:V([`evenodd`,`nonzero`]).optional(),fill:A().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:A().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:M().min(0).max(50).optional(),paddingRatio:M().min(0).max(.25).optional()}).strict().optional(),installation:eu.optional(),notice:$l.optional(),launchCommand:H(!0).optional(),links:I({website:Ql.optional(),documentation:Ql.optional(),installation:Ql.optional()}).strict().optional()};I({manifestVersion:H(1),...tu,adapterApiVersion:M().int().positive(),entry:Zl,icon:Zl.optional()}).strict();let nu=A().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),ru=I({...tu,icon:nu.optional()}).strict();I({}).strict(),I({plugins:F(ru.extend({id:Xl})).max(128)}).strict(),I({version:H(1),enabled:F(Yl).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let iu=Jl,au=V([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),ou=V([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),su=A().trim().min(1).max(128);function cu(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 lu=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),uu=Zl.refine(e=>cu(e)!==void 0&&lu(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),du=A().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Ys({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 fu(e){return L({en:e,"zh-CN":e})}let pu=fu(A().trim().min(1)),mu=F(ou).max(ou.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),hu=F(au).max(au.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),gu={key:A().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:pu,description:pu.optional()},_u={...gu,step:M().positive().optional(),default:M().optional()},vu=L({value:A(),label:pu}),yu=z(`type`,[L({...gu,type:H(`boolean`),default:P().optional()}),L({...gu,type:H(`string`),placeholder:pu.optional(),default:A().optional()}),L({..._u,type:H(`number`),min:M().optional(),max:M().optional()}),L({..._u,type:H(`range`),min:M(),max:M()}),L({...gu,type:H(`select`),options:F(vu).min(1),default:A().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`)}}),bu=I({manifestVersion:N().positive(),id:iu,name:R([su,fu(su)]),version:A().min(1).max(128),desktopApi:N().positive()}).passthrough().extend({manifestVersion:H(1),desktopApi:H(1),description:L({en:A().max(4096),"zh-CN":A().max(4096).optional()}).optional(),author:A().trim().min(1).max(128).optional(),repository:du.optional(),details:L({en:A().max(16384),"zh-CN":A().max(16384).optional()}).optional(),icon:uu.optional(),screenshots:F(uu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:L({script:Zl,style:Zl.optional()}).optional(),backend:L({script:Zl.refine(lu)}).optional(),slots:hu.default(()=>[]),settingsSchema:F(yu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:mu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),xu=A().regex(/^[a-f0-9]{64}$/u),Su=L({state:V([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:xu.optional(),error:A().optional(),conflictWith:iu.optional()});L({controllerPid:N().positive(),targetId:A().nullable(),updatedAt:rl(),handledReloadToken:qs().optional(),extensions:B(A(),Su),surfaces:B(A(),Su).optional()});let Cu=V([`official`,`community`]);function wu(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Tu=du.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||wu(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`),Eu=L({id:iu,version:A().trim().min(1).max(128),name:pu.extend({en:su,"zh-CN":su}),description:fu(A().trim().min(1).max(4096)),details:fu(A().trim().min(1).max(16384)).optional(),author:A().trim().min(1).max(128),repository:du,stars:M().int().min(0).optional(),downloads:M().int().min(0).optional(),categories:mu.optional(),trustTier:Cu.default(`community`),icon:du.optional(),screenshots:F(du).max(4).optional(),downloadUrl:Tu,sha256:xu,slots:hu.optional(),publishedAt:A().optional(),updatedAt:A().optional(),minCodexHostVersion:A().optional()});L({schemaVersion:H(1),generatedAt:A(),extensions:F(Eu).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Du=A().trim().min(1).max(128),Ou=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,ku=iu.refine(e=>!Ou.test(e),`Reserved extension ID`),Au=V([`desktop`,`web`]),ju=xu,Mu=qs(),Nu=Zl.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Ou.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),Pu=bu.shape,Fu=(e,t=0)=>L({en:A().trim().min(t).max(e),"zh-CN":A().trim().min(t).max(e)}),Iu=e=>Nu.refine(t=>t.endsWith(e),`Expected a ${e} file`),Lu=Iu(`.mjs`),Ru=Iu(`.css`).optional(),zu=e=>e.normalize(`NFC`).toLowerCase(),Bu=L({manifestVersion:H(2),id:ku,name:Fu(128,1),version:A().trim().min(1).max(128),description:Fu(4096),details:Fu(16384).optional(),author:Pu.author,repository:Pu.repository,icon:Pu.icon.refine(e=>e===void 0||Nu.safeParse(e).success),screenshots:Pu.screenshots.refine(e=>e===void 0||e.every(e=>Nu.safeParse(e).success)),categories:Pu.categories,settingsSchema:Pu.settingsSchema,slots:Pu.slots.removeDefault().optional(),page:L({apiVersion:H(1),entry:Lu,style:Ru,title:Fu(128,1).optional()}).optional(),widget:L({apiVersion:H(1),entry:Lu,style:Ru}).optional(),desktop:L({apiVersion:H(1),script:Iu(`.js`),style:Ru}).optional(),web:L({apiVersion:H(1),entry:Lu.optional(),style:Ru}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:L({apiVersion:H(1),entry:Lu}).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||zu(e)!==zu(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Vu({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 Hu=Du,Uu=N().nonnegative(),Wu=L({revision:Uu,enabled:F(ku).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)}),{downloadUrl:Gu,...Ku}=Eu.shape,qu=I({...Ku,id:ku,format:H(`codexhost`),targets:F(Au).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:L({page:N().positive().optional(),widget:N().positive().optional(),desktop:N().positive().optional(),web:N().positive().optional(),backend:N().positive().optional()}),downloadUrl:Gu.refine(e=>e.startsWith(`https://`),`Expected HTTPS`)}).refine(({targets:e,apis:t})=>{let n=Vu({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`);I({schemaVersion:H(2),generatedAt:A().min(1),extensions:F(qu).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:du,fetchedAt:rl(),cached:P()});let Ju={id:ku},Yu={...Ju,activationId:Mu,digest:ju},Xu={...Ju,activationId:Yu.activationId.optional()},Zu=A().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`),Qu=A().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function $u(e){return A().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 ed=L({type:H(`github`),repository:A().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Qu.optional(),tag:Qu.optional(),asset:A().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Nu.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),td=R([L({type:H(`catalog`),...Ju}),ed,L({type:H(`zip`),base64:$u(67108864).min(4)}),L({type:H(`zip`),localZipPath:Zu}),L({type:H(`localDir`),localDir:Zu})]),nd=z(`type`,[L({type:H(`catalog`),...Ju}),ed,L({type:H(`zip`)}),L({type:H(`localDir`)})]),rd=L({...Yu,manifest:Bu,installedAt:rl(),source:nd.optional()}),id=e=>A().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),ad={desktopConflictWith:ku.optional()},od=V([`none`,`inactive`,`starting`,`running`,`failed`]),sd=z(`state`,[rd.extend({state:H(`valid`),enabled:P(),...ad,iconDataUrl:id(131072).optional(),screenshotDataUrls:F(id(524288)).max(4).optional(),backendState:od.optional(),backendError:A().optional()}),L({state:V([`invalid`,`incompatible`]),id:A().min(1),enabled:P(),error:A()})]);L({revision:Uu,configuration:Wu,diagnostics:F(A()),extensions:F(sd)}),L({revision:Uu,extensions:F(rd.extend({...ad,settingsRevision:Uu})).max(64)});let Y={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`},cd=Object.freeze(Object.values(Y));new Set(cd),L({});let ld={expectedRevision:Uu};L({...Ju,...ld}),rd.extend({replaced:P()}),z(`state`,[L({state:H(`saved`),configuration:Wu}),L({state:H(`revision-conflict`),revision:Uu})]),L({...Xu,digest:Yu.digest.optional(),path:Nu}),L({mimeType:A().min(1),base64:$u(16777216),digest:Yu.digest}),L({settingsRevision:Uu,values:ll}),Y.list,Y.snapshot,Y.catalog,L({forceRefresh:P().optional()}),Y.install,L({source:td}),Y.update,L({...Ju,expectedDigest:Yu.digest,expectedActivationId:Yu.activationId.optional(),source:td.optional()}),Y.enable,Y.disable,Y.uninstall,L({...Ju,removeData:P().optional(),expectedDigest:Yu.digest.optional()}),L({...Ju,removed:P()}),Y.recover,L({expectedRevision:ld.expectedRevision.optional()}),Y.asset,Y.settingsGet,L(Xu),Y.settingsSet,L({...Xu,expectedSettingsRevision:Uu,values:ll}),Y.backendInvoke,L({...Xu,method:Hu,params:U.optional()}),L({result:U}),I({threadId:G}).strict(),I({confirmed:P()}).strict(),[...cd],I({sections:F(I({id:A().min(1),name:A().min(1),threads:F(ll)}).strict())}).strict(),I({threadId:A().min(1).max(1024),sectionId:A().min(1).max(1024).nullable()}).strict(),I({threadIds:F(A().min(1))}).strict(),I({threadId:A().min(1).max(1024),pinned:P()}).strict(),I({}).strict(),I({parents:B(A().min(1),A().min(1))}).strict(),I({prompt:A().max(16384).optional()}).strict(),I({projects:F(I({id:A(),name:A(),rootPaths:F(A())})),assignments:B(A(),A()),projectless:F(A()),pinned:F(A()),sectionProjects:B(A(),F(A())).optional()});let ud=B(A(),_c()),dd=I({epoch:A().uuid(),sequence:M().int().nonnegative()});z(`type`,[I({type:H(`skills-changed`),cursor:dd,cwd:A().optional()}),I({type:H(`harness-inspection-changed`),cursor:dd,harnessId:A().min(1)}),I({type:H(`display-settings-changed`),cursor:dd}),I({type:H(`preferences-changed`),cursor:dd,revision:M().int().nonnegative()}),I({type:H(`extensions-changed`),cursor:dd,revision:Uu}),I({type:H(`hello`),version:H(1),cursor:dd,reset:P()}),I({type:H(`changed`),cursor:dd,threadId:A().min(1),method:A().min(1)})]);let fd=z(`type`,[I({type:H(`text`),id:A(),prompt:A(),secret:P().optional(),optional:P().optional()}),I({type:H(`choice`),id:A(),prompt:A(),multiple:P(),allowOther:P(),optional:P().optional(),options:F(I({value:A(),label:A(),description:A().optional()}))})]),pd=z(`type`,[I({type:H(`approval`),title:A(),description:A().optional(),subject:_c().optional(),actions:F(I({id:A(),label:A(),effect:A()}))}),I({type:H(`question`),title:A().optional(),questions:F(fd)})]),md=I({requestId:R([A(),M().int()]),threadId:A(),kind:V([`approval`,`question`]),interaction:pd,request:ud}),hd=I({id:A().min(1),clientUserMessageId:A().min(1),input:F(ud),presentationInput:F(ud).nullable().optional()}).passthrough();I({fields:F(I({path:F(R([A(),M().int().nonnegative()])),originalLength:M().int().nonnegative()}))});let gd=I({id:A().min(1),status:A().min(1),codexhostTurnOutcome:I({status:H(`unknown`),reason:A()}).optional(),items:F(I({id:A().min(1),type:A().min(1)}).passthrough()),codexhostFileOperations:F(I({beforeItemId:A().nullable(),item:I({id:A().min(1),type:A().min(1)}).passthrough()})).optional(),error:I({message:A().optional()}).passthrough().nullable().optional(),fingerprint:A().min(1).optional(),unchanged:H(!0).optional()}).passthrough(),_d=I({id:A().min(1).max(512),fingerprint:A().min(1).max(128)});I({threadId:A().min(1),knownTurns:F(_d).max(64).optional(),truncateToolOutput:P().optional()});let vd=I({harnessId:A().min(1),nativeSessionId:A().min(1)});I({cursor:dd,activeTurnId:A().min(1).nullable().optional(),command:I({name:A().min(1),turn:gd,subsequentTurnId:A().min(1).optional()}).optional(),thread:I({id:A().min(1),cwd:A(),modelProvider:A().min(1),createdAt:M(),updatedAt:M(),status:I({type:A()}).passthrough(),name:A().nullable().optional(),preview:A().optional(),codexhostImportSource:vd.optional(),turns:F(gd).length(0)}).passthrough(),turnsPage:I({data:F(gd).max(5),nextCursor:A().nullable()}),configuration:I({native:I({model:A().min(1).max(1024).optional(),reasoningEffort:A().min(1).max(128).optional()}).optional(),effectiveModel:q.optional(),effectiveThinkingOptionId:J.optional(),effectivePermissionModeId:vl.optional()}),queue:I({items:F(hd),pausedReason:V([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:F(md)}),I({version:H(1),owner:H(`service`).optional(),pid:M().int().positive(),port:M().int().min(1).max(65535),token:A().regex(/^[0-9a-f]{64}$/u),startedAt:M(),epoch:A().uuid()}),I({epoch:A().uuid(),threadId:A().min(1),requestId:R([A(),M().int()]),result:ud}),I({includeArchived:P().optional(),officialCursor:I({live:A().nullable(),archived:A().nullable().optional()}).strict().optional(),scope:I({cwd:A().min(1).max(4096),excludeCwds:F(A().min(1).max(4096)).max(1024)}).strict().optional()}).strict(),I({threads:F(ll),ownership:F(ql),archivedThreadIds:F(G),officialCursor:I({live:A().nullable(),archived:A().nullable().optional()}).strict().optional()}).strict();let yd=V([`running`,`waiting`,`idle`,`unknown`]),bd=L({harnessId:W,title:A().optional(),status:yd,archived:P()}),xd=L({revision:N().nonnegative(),parents:B(G,G),nodes:B(G,bd),truncated:P()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,nodes:t})=>Object.entries(e).every(([e,n])=>Object.hasOwn(t,e)&&Object.hasOwn(t,n)),`Missing Thread tree node`),Sd=A().min(1).max(128);L({});let Cd=L({subscriptionId:Sd});L({}),Cd.extend({snapshot:xd});let wd=A().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);I({available:P()}).strict(),I({path:A().min(1),mimeType:wd}).strict();let Td=V([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);z(`ok`,[I({ok:H(!0),text:A()}).strict(),I({ok:H(!1),error:I({code:Td}).strict()}).strict()]),I({threadId:G.optional(),cwd:A().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Ed=I({name:A().min(1).regex(/^[^\s[\]]+$/u),description:A().optional(),path:A().min(1),scope:V([`project`,`global`]),source:A().min(1)}).strict();I({revision:M().int().nonnegative(),complete:P(),skills:F(Ed),warnings:F(A()).optional()}).strict(),I({cwd:A().min(1).optional()}).strict();let Dd=I({kind:V([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:A().min(1)}).strict(),Od=z(`status`,[I({status:H(`not-installed`)}),I({status:H(`not-running`)}),I({status:H(`not-logged-in`)}),I({status:H(`https-disabled`)}),I({status:H(`not-serving`),command:A()}),I({status:H(`occupied`),target:A()}),I({status:H(`serving`),url:A(),funnel:P()}),I({status:H(`error`),message:A()})]);I({state:Od,error:A().optional()}).strict();let kd=z(`status`,[I({status:H(`on`)}),I({status:H(`off`)}),I({status:H(`invalid`),reason:A()})]),Ad=I({lan:P(),autostart:kd}).strict(),jd=I({expiresAt:A().optional(),issuing:P(),failure:I({detail:A().optional(),retryAt:A(),paused:P()}).optional()}),Md=z(`status`,[I({status:H(`off`),reason:V([`invite`,`name-taken`,`banned`]).optional()}),I({status:H(`connecting`),reason:V([`full`,`unreachable`]).optional()}),I({status:H(`connected`),url:A(),certificate:jd}),I({status:H(`missing-certificate`),url:A(),certificate:jd}),I({status:H(`stopped`),reason:V([`replaced`,`rejected`,`unsupported-version`])})]);A().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()),A().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let Nd=V([`official`,`self-hosted`]);I({secret:A().min(1),lastUsedAt:M().nullable(),networkUrls:F(Dd),directCandidates:F(Dd).optional(),tailscale:Od,background:Ad.optional(),relay:I({state:Md,enabled:P(),kind:Nd,officialHost:A(),customHost:A().optional(),officialHostname:A().optional(),customHostname:A().optional(),quotaUntil:A().optional()}).strict().optional()}).strict();let Pd=L({threadId:A().min(1).max(1024),view:V([`result`,`messages`]),from:M().int().min(1).max(2**53-1).optional(),to:M().int().min(1).max(2**53-1).optional()}),Fd=I({id:A().min(1).max(256),harnessId:A().min(1),label:A().min(1).max(512),provider:V([`openai-codex`,`xai`])}).strict(),Id=A().regex(/^[a-z][a-z0-9-]{0,47}$/),Ld=I({name:Id,source:Fd,importedAt:A()}).strict(),Rd=z(`action`,[I({action:H(`list`)}).strict(),I({action:H(`import`),sourceId:A().min(1).max(256),name:Id,confirmed:H(!0)}).strict(),I({action:H(`reimport`),sourceId:A().min(1).max(256),name:Id,confirmed:H(!0)}).strict(),I({action:H(`remove`),name:Id,confirmed:H(!0)}).strict()]),zd=I({provider:A().min(1).max(128),type:V([`oauth`,`api_key`,`unknown`]),label:A().min(1).max(512).optional(),vendor:V([`openai-codex`,`xai`]).optional()}).strict();I({sources:F(Fd),targets:F(I({harnessId:A(),providers:F(V([`openai-codex`,`xai`])),imports:F(Ld),others:F(zd).default([])}).strict())}).strict(),I({targetHarnessId:A().min(1).max(128).optional(),request:Rd}).strict(),I({events:P()});let Bd=F(L({agent:A().min(1).max(128),section:V([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);L({entries:Bd.nullable()}),L({}),L({entries:Bd,initializeOnly:P().optional()});let Vd=L({enabled:P(),timeoutMinutes:M().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let Hd=A().regex(/^external$/u),Ud=W.transform(e=>String(e)),Wd=L({model:q.optional(),thinkingOptionId:J.optional(),permissionModeId:vl.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),Gd=L({lastHarness:W.optional(),byHarness:B(Ud,Wd)}),Kd=L({model:q.optional(),thinkingOptionId:J.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),qd=L({byHarness:B(Ud,Kd)}),Jd=A().min(1).max(1024),Yd=L({idleRelease:Vd.optional(),favorites:B(Ud,F(Jd).max(2048)).default({}),newThread:Gd.optional(),delegation:qd.optional()});L({scope:Hd,revision:M().int().nonnegative(),values:Yd}),L({scope:Hd.default(`external`)});let Xd=z(`kind`,[L({kind:H(`idleRelease`),value:Vd}),L({kind:H(`favorite`),harnessId:W,modelId:Jd,enabled:P()}),L({kind:H(`favorites`),harnessId:W,modelIds:F(Jd).max(2048)}),L({kind:H(`newThread`),lastHarness:W.optional(),harnessId:W.optional(),configuration:Wd.optional()}),L({kind:H(`delegation`),harnessId:W,configuration:Kd.nullable()})]);L({scope:Hd.default(`external`),operations:F(Xd).min(1).max(256),initializeOnly:P().optional(),expectedRevision:M().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`})}),L({version:H(1),revision:M().int().nonnegative(),scopes:B(Hd,Yd)});let Zd=M().finite().nonnegative(),Qd=L({input:Zd,output:Zd,cacheRead:Zd.optional(),cacheWrite:Zd.optional(),cacheWrite1h:Zd.optional()}),$d=A().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);L({path:A(),entries:F(L({key:A(),price:Qd})),error:A().nullable()}),L({}),L({key:$d,price:Qd.nullable(),previousKey:$d.optional()}),L({model:$d});let ef=L({official:P().optional(),canonicalModelId:A().min(1).optional(),provider:A().min(1).max(512),model:A().min(1).max(512),price:Qd});L({price:Qd.nullable(),suggestions:F(ef).max(6).optional()});let tf=[`today`,`7d`,`30d`,`90d`,`all`],X=M().int().min(0).max(2**53-1),nf=A().regex(/^\d{4}-\d{2}-\d{2}$/u),rf=A().min(1).max(128),af=A().min(1).max(512),of=A().min(1).max(4096);L({range:V(tf),timeZone:A().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:rf.optional(),model:af.nullable().optional(),project:of.nullable().optional(),date:nf.optional()});let sf=L({requests:X,inputTokens:X,cachedInputTokens:X,cacheWriteInputTokens:X,cacheKnownInputTokens:X,cacheHitCachedInputTokens:X,cacheHitInputTokens:X,outputTokens:X,reasoningOutputTokens:X,costUsd:M().finite().min(0),unpricedRequests:X,unmeteredRequests:X}),cf=sf.shape,lf=L({harness:rf,sessionId:A().min(1).max(512),project:of.nullable(),title:A().min(1).max(200).optional(),models:F(af).max(16),firstAtMs:X,lastAtMs:X,...cf});L({range:V(tf),from:nf.nullable(),to:nf,filters:L({harness:rf.nullable(),model:af.nullable(),unknownModel:P(),project:of.nullable(),unknownProject:P(),date:nf.nullable()}),reading:L({complete:P(),sources:X,read:X}),failures:F(L({harness:rf,message:A().max(2048)})).max(256),options:L({harnesses:F(rf).max(256),models:F(af.nullable()).max(4096),projects:F(of.nullable()).max(4096)}),modelLabels:F(L({harness:rf,model:af,label:af})).max(4096).optional(),credits:F(L({harness:rf,model:af.nullable(),credits:M().finite().min(0),reportedRequests:X,requests:X})).max(4096).optional(),totals:sf,daily:F(L({date:nf,harness:rf,...cf})).max(2e5),hourly:F(L({weekday:M().int().min(0).max(6),hour:M().int().min(0).max(23),...cf})).max(168),byHarness:F(L({harness:rf,...cf})).max(256),byModel:F(L({model:af.nullable(),...cf,harnessPricedRequests:X})).max(4096),byProject:F(L({project:of.nullable(),...cf})).max(4096),sessions:F(lf).max(100),recentSessions:F(lf).max(100).optional()}),I({threadId:G}),I({discarded:P()});let uf=z(`type`,[I({id:A().min(1),type:H(`choice`),prompt:A(),options:F(I({value:A().min(1),label:A(),description:A().optional()})).min(1),multiple:P(),allowOther:P(),optional:P()}),I({id:A().min(1),type:H(`text`),prompt:A(),multiline:P(),secret:H(!1),optional:P(),placeholder:A().optional(),prefill:A().optional()})]),df=I({interactionId:A().min(1),turnId:A().min(1),title:A().optional(),questions:F(uf).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});L({threadId:A().min(1)}),I({questions:F(df)}),L({threadId:A().min(1),turnId:A().min(1),interactionId:A().min(1),answers:B(A(),F(A())),cancelled:P().default(!1)}),I({accepted:H(!0)});let ff=`codexhostActiveTurnId`,pf=/* @__PURE__ */ new Set([ff,`codexhostTurnChanges`,`codexhostToolOutput`]),mf=I({path:A(),oldText:A().nullable(),newText:A()});I({sessionId:A().min(1),turn:M().int().nonnegative(),path:A().min(1).optional()}),I({diffs:F(mf)}),L({}),L({}),I({reference:I({sessionId:A().min(1),epoch:A().min(1),turn:M().int().nonnegative(),seq:M().int().nonnegative(),callId:A().min(1),part:M().int().nonnegative(),version:A().min(1)}),length:M().int().nonnegative(),bytes:M().int().nonnegative()}),L({title:A().trim().min(1).max(200),type:V([`info`,`warning`,`danger`]),body:A().trim().min(1).max(16384)}),L({}),L({url:A().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status`.split(`.`));let hf=V([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),gf=V([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);L({threadId:A(),title:A(),harnessId:A(),state:hf,reason:gf,inactiveMs:M().nonnegative()}),L({threadId:G,turnId:gl});let _f=I({email:A().trim().min(1).max(320).optional(),label:A().trim().min(1).max(256).optional(),plan:A().trim().min(1).max(128).optional(),credits:jl.optional(),balance:Ml.optional()}).strict();function vf(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 yf=vf(_f),bf={harnessId:W,harnessName:A().trim().min(1).max(128)},xf=I(bf).strict();I({}).strict(),I({sources:F(xf).max(128)}).strict(),I({harnessId:W,refresh:P().optional()}).strict(),I({...bf,account:yf.nullable(),accounts:F(yf).max(8).optional()}).strict(),I({refresh:P().optional()}).strict(),I({accounts:F(vf(_f.extend(bf))).max(128)}).strict(),I({harnessId:Xl,model:q.optional(),thinkingOptionId:J.optional(),permissionModeId:vl.optional(),prewarm:H(!0).optional()}).strict();let Sf=A().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);I({harnessId:Xl}).strict().extend({path:Sf.nullable()}),I({path:Sf.nullable(),restartRequired:P()}).strict(),I({harnessId:W,action:V([`check`,`update`,`install`]),confirmedVersion:A().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let Cf=I({currentVersion:A().min(1).max(128),latestVersion:A().min(1).max(128),updateAvailable:P(),canUpdate:P(),latestVerifiedVersion:A().min(1).max(128).optional(),confirmationRequired:H(!0).optional(),versionKind:V([`cli`,`application`]).optional(),manualUpdateUrl:Ys().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:A().max(2048).optional(),messageCode:A().min(1).max(128).optional(),notice:ml.optional(),latestVersionKind:V([`unknown`,`tracking-branch`]).optional()}).strict();I({taskId:A().uuid()}).strict(),z(`status`,[I({taskId:A().uuid(),status:H(`running`)}).strict(),I({taskId:A().uuid(),status:H(`succeeded`),result:Cf}).strict(),I({taskId:A().uuid(),status:H(`failed`),error:I({code:M().int(),message:A().min(1).max(2048)}).strict()}).strict()]);let wf=A().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Tf=A().trim().min(1),Ef=V([`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`]),Df=I({accountId:wf,label:Tf.max(256),email:A().email().max(320).optional(),planType:Ef.optional()}).strict(),Of=V([`ready`,`unavailable`]);I({version:H(2),currentAccountId:wf.nullable(),phase:Of,revision:M().int().nonnegative(),instanceId:Tf.max(1024).optional(),accounts:F(Df).max(1)}).strict(),I({accountId:wf,refresh:P().optional()}).strict(),I({accountId:wf,usage:Tl.nullable(),accountCredits:jl.optional(),freshness:V([`live`,`cached`]),observedAt:A().datetime().nullable()}).strict();let kf=1e3,Af=A().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),jf=Af.max(1024),Mf=I({nativeSessionId:jf,title:Af.max(4096).nullable(),updatedAt:M().int().nonnegative().max(864e13),cwd:Af.max(16384),running:P().nullable()}).strict();I({}).strict(),I({harnesses:F(I({harnessId:Xl,name:Af.max(128)}).strict()).max(128)}).strict(),I({harnessId:Xl,query:A().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:M().int().nonnegative().safe().optional(),limit:M().int().min(1).max(kf).optional()}).strict(),I({candidates:F(Mf).max(kf),total:M().int().nonnegative().safe()}).strict(),I({harnessId:Xl,nativeSessionId:jf}).strict(),I({threadId:Af.max(1024).pipe(G)}).strict();let Nf=A().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Pf=jf,Ff=Mf;I({}).strict(),I({candidates:F(Ff).max(1e3)}).strict(),I({nativeSessionId:Pf}).strict(),I({threadId:Nf.max(1024).pipe(G)}).strict(),I({threadId:G,lastTurnId:gl}).strict(),I({threadId:G}).strict();let If=A().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();I({commands:F(I({id:If,invocation:A().min(1).max(128),label:A().trim().min(1).max(128),description:A().trim().min(1).max(512).optional(),localizations:pl.optional(),argumentMode:V([`none`,`text`]),kind:V([`command`,`skill`]).optional()}).strict()),warnings:F(A().min(1)).optional(),source:V([`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)}),I({harnessId:W,cwd:A().min(1).optional()}).strict(),I({threadId:G}).strict(),I({threadId:G,commandId:If,turnId:gl.optional(),arguments:ll.optional()}).strict(),I({accepted:H(!0),turnId:gl.optional()}).strict();let Lf=H(`2.0`).optional(),Z=yc().optional(),Rf=A().min(1),zf=R([A(),M().int()]),Bf=I({code:M().int(),message:A(),data:U.optional()}).catchall(U).superRefine(il([`data`]));R([I({jsonrpc:Lf,id:zf,method:Rf,params:U.optional(),result:Z,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`params`,`result`,`error`])),I({jsonrpc:Lf,id:Z,method:Rf,params:U.optional(),result:Z,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`id`,`params`,`result`,`error`])),I({jsonrpc:Lf,id:zf,method:Z,params:Z,result:U,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`method`,`params`,`error`])),I({jsonrpc:Lf,id:zf,method:Z,params:Z,result:Z,error:Bf}).catchall(U).superRefine(il([`jsonrpc`,`method`,`params`,`result`]))]);let Vf=A().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});L({harnessId:W,nativeSessionId:Vf,locator:U.optional(),formatVersion:H(1)}).superRefine(il([`locator`])),L({harnessId:W,nativeSessionId:Vf,nativeTurnKey:Vf,formatVersion:H(1)}),L({harnessId:W,nativeSessionId:Vf,checkpointId:Vf,locator:U.optional(),formatVersion:H(1)}).superRefine(il([`locator`]));let Hf=A().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Uf=V([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Wf=L({version:Hf,installation:Uf,phase:V([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:M().int().nonnegative(),downloadedBytes:M().int().nonnegative().optional(),totalBytes:M().int().positive().optional(),error:A().min(1).max(500).nullable(),serviceStopOutput:A().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`})});L({});let Gf=A().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`);L({currentVersion:Hf,installation:Uf.nullable(),latestVersion:Hf.nullable(),updateAvailable:P(),installationAvailable:P(),releaseNotes:A().min(1).max(2e4).nullable(),releaseNotesUrl:Gf.nullable(),status:Wf.nullable(),error:A().min(1).max(500).nullable()}),L({status:Wf}),L({status:Wf.nullable()});let Kf=L({icon:A().min(1).max(16).optional(),title:A().min(1).max(120),body:A().min(1).max(1200),contributors:F(A().min(1).max(39)).max(30)}),qf=L({summary:A().min(1).max(600).optional(),themes:F(Kf).min(1).max(12)}),Jf=L({version:Hf,publishedAt:rl(),url:A().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:qf.nullable(),en:qf.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});L({manual:P().optional()}),L({announcement:Jf.nullable(),unread:P()}),L({version:Hf}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Yf=V([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);I({runningVersion:A().nullable(),installedVersion:A().nullable(),restartRequired:P(),remote:P(),updateSupported:P(),update:I({phase:Yf,targetVersion:A().nullable(),error:A().nullable()})});let Xf=I({version:A().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();I({hostname:A().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable(),action:V([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:P().optional(),version:A().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),I({state:V([`installed`,`not-installed`])}).strict();let Q=A().min(1).max(1024),Zf={hostId:Q.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},$={...Zf,threadId:Q},Qf=A().min(1).max(8e3),$f={text:Qf,requestId:Q};z(`accepted`,[I({accepted:H(!0),startQueuedItemId:Q.optional()}),I({accepted:H(!1),code:V([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:A()})]),z(`available`,[I({available:H(!1)}),I({available:H(!0),items:F(I({id:Q,clientUserMessageId:Q,preview:A().max(801)})).max(100)})]);let ep=z(`kind`,[L({kind:H(`hosts`)}),L({kind:H(`create`),...Zf,cwd:A().min(1).max(8192),epoch:Q}),L({kind:H(`projectHarnesses`),...Zf,epoch:Q}),L({kind:H(`inspectHarness`),...Zf,epoch:Q,cwd:A().min(1).max(8192),harnessId:Q}),L({kind:H(`startSelected`),...Zf,epoch:Q,cwd:A().min(1).max(8192),harnessId:Q,model:A().min(1).max(4096),serviceTier:V([`priority`,`ultrafast`]).optional(),reasoningEffort:Q.optional()}),L({kind:H(`status`),...$}),L({kind:H(`list`),...Zf,cursor:A().nullable(),archived:P(),includeLoaded:H(!0).optional()}),L({kind:H(`read`),...$,page:L({cursor:A().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:V([`asc`,`desc`]).optional(),limit:M().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),L({kind:H(`usage`),...$,epoch:Q}),L({kind:H(`configure`),...$,epoch:Q,modelId:Q.optional(),serviceTier:Fl.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`}),L({kind:H(`prompt`),...$,epoch:Q,text:Qf,requestId:Q.optional()}),L({kind:H(`queue`),...$,epoch:Q}),L({kind:H(`delivery`),...$,epoch:Q,action:z(`kind`,[L({kind:H(`enqueue`),...$f}),L({kind:H(`steer`),...$f,turnId:Q}),L({kind:H(`remove`),itemId:Q}),L({kind:H(`start`),itemId:Q,onlyIfHead:H(!0).optional()})])}),L({kind:H(`interrupt`),...$,epoch:Q,turnId:Q}),L({kind:H(`rename`),...$,epoch:Q,name:A().min(1).max(512)}),L({kind:H(`archive`),...$,epoch:Q,archived:P()}),L({kind:H(`respond`),...$,epoch:Q,requestId:R([Q,M().int()]),result:B(A(),_c())})]),tp=A().min(1).max(1024),np=I({hostId:tp,displayName:A().min(1).max(1024),source:V([`codex-managed`,`discovered`]),sshAlias:A().max(1024).nullable(),sshHost:A().min(1).max(1024),sshPort:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable(),autoConnect:P(),connectionAnalyticsId:A().max(1024).optional()}),rp=L({displayName:A().min(1).max(1024),hostname:A().min(1).max(1024),sshPort:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable()});z(`action`,[L({action:H(`session`),operation:ep}),L({action:H(`list`)}),L({action:H(`catalog`)}),L({action:H(`read-thread`),hostId:tp.refine(e=>e!==`local`),input:Pd}),L({action:H(`save`),draft:rp,previous:np.nullable()}),L({action:H(`remove`),previous:np}),L({action:H(`connect`),hostId:tp,enabled:P()}),L({action:H(`state`),hostId:tp}),L({action:H(`runtime`),hostId:tp}),L({action:H(`update`),hostId:tp.refine(e=>e!==`local`),version:Xf.shape.version})]),R([L({result:U}),L({error:L({code:M().int(),message:A()})})]),L({prompt:A().trim().min(1).max(2e3),cwd:A().max(4096).nullable()}),A().trim().min(1).max(60).nullable();let ip=A().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),ap=R([A(),I({en:A()}).catchall(A())]),op=I({title:ap.optional(),description:ap.optional(),icon:A().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:A().optional()});I({extensions:F(I({id:ip,name:A().min(1).max(214),version:A().min(1).max(128),format:H(`dsh`),supportedTargets:Dc([H(`web`)]),enabledTargets:F(H(`web`)).max(1),source:A().min(1).max(4096),projectUrl:A().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:A(),meta:op.optional(),loadError:A().optional()})),loadedIds:F(ip),safeMode:P(),storeError:A().optional()});let sp=A().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}/`);I({spec:A().trim().min(1).max(4096),registry:sp.optional()}).strict(),I({id:ip,enabled:P()}).strict(),I({id:ip}).strict();let cp=A().regex(/^[a-zA-Z0-9_-]{1,64}$/u),lp=A().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),up=V([`relay`,`tailscale`,`lan`,`custom`]),dp=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],fp=V(dp);new Set(dp);let pp=V([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]);I({peers:F(I({peerId:cp,hostId:lp,name:A().min(1).max(120),color:fp.optional(),origin:A().min(1).max(2048),transportKind:up,encrypted:P(),enabled:P(),state:pp,latencyMs:M().int().nonnegative().optional(),version:A().max(128).optional(),platform:A().max(64).optional(),hostname:A().max(255).optional(),homeDir:A().max(4096).optional(),lastError:A().max(1e3).optional(),projectCount:M().int().nonnegative(),createdAt:A(),updatedAt:A()}))}),I({connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional(),name:A().trim().min(1).max(120).optional(),color:fp.optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),I({peerId:cp,name:A().trim().min(1).max(120).optional(),color:fp.nullable().optional(),connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional(),enabled:P().optional()}),I({peerId:cp}),I({removed:P()}),I({peerId:cp.optional(),connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let mp=I({id:A().min(1).max(1024),name:A().min(1).max(512),path:A().min(1).max(8192)});I({ok:P(),latencyMs:M().int().nonnegative().optional(),origin:A().max(2048).optional(),transportKind:up.optional(),encrypted:P().optional(),version:A().max(128).optional(),platform:A().max(64).optional(),hostname:A().max(255).optional(),homeDir:A().max(4096).optional(),projectCount:M().int().nonnegative().optional(),projects:F(mp).optional(),error:A().max(1e3).optional()});let hp=I({id:A().min(1).max(1024),name:A().min(1).max(512),path:A().min(1).max(8192),threadIds:F(A().min(1).max(1024))}),gp=I({attachments:H(1).optional(),workspaceFiles:H(1).optional(),officePreview:H(1).optional()}),_p=I({version:A().max(128),platform:A().max(64),hostname:A().max(255),homeDir:A().max(4096).optional(),epoch:A().min(1).max(256),projects:F(hp),capabilities:gp.optional()});L({threadId:A().min(1).max(1024),scope:A().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:A().min(1).max(256).optional(),mode:V([`queue`,`steer`]).optional(),expectedTurnId:A().min(1).max(1024).nullable().optional(),content:F(z(`type`,[L({type:H(`text`),text:A()}),L({type:H(`file`),receiptId:A().min(1).max(128)})])).min(1).max(64)});let vp=I({ok:H(!1),error:I({code:A(),message:A(),details:B(A(),_c()).optional()})});R([I({ok:H(!0),value:I({receiptId:A().min(1),file:I({attachmentId:A(),name:A(),bytes:M().int().nonnegative()})})}),vp]),R([I({ok:H(!0),value:I({accepted:H(!0)})}),vp]);let yp=I({name:A().min(1).max(512),path:A().min(1).max(8192),kind:H(`directory`)});I({peerId:cp,path:A().min(1).max(8192).optional()}),I({path:A().min(1).max(8192),parentPath:A().min(1).max(8192).nullable(),homeDir:A().min(1).max(8192).optional(),entries:F(yp)}),I({peerId:cp,parentPath:A().min(1).max(8192),name:A().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),I({path:A().min(1).max(8192),name:A().min(1).max(255)}),I({peerId:cp,path:A().min(1).max(8192),title:A().trim().min(1).max(255).optional()}),I({peerId:cp,workspaceId:A().min(1).max(1024),title:A().trim().min(1).max(255)}),I({peerId:cp,workspaceId:A().min(1).max(1024)}),I({workspaceId:A().min(1).max(1024).optional(),manifest:_p}),H(1);function bp(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 Co(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;Co(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 wo=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),To=[`oneOf`,`anyOf`];function Eo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Do(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!wo.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]??Eo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ae(n,r,e.length===1?e[0]:Do(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=Eo(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 Oo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of wo)if(t in e)return;let n=t.filter(e=>To.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Do(t);else{let e=n[0],i=To.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=>Do([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,vo(e,r))}function ko(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)):vo(i,s),vo(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())Co(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)??[])Oo(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)}vo(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:jo(t,`input`,e.processors),output:jo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function E(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return E(r.element,n);if(r.type===`set`)return E(r.valueType,n);if(r.type===`lazy`)return E(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return E(r.innerType,n);if(r.type===`intersection`)return E(r.left,n)||E(r.right,n);if(r.type===`record`||r.type===`map`)return E(r.keyType,n)||E(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:E(r.in,n)||E(r.out,n);if(r.type===`object`){for(let e in r.shape)if(E(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(E(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(E(e,n))return!0;return!!(r.rest&&E(r.rest,n))}return!1}let Ao=(e,t={})=>n=>{let r=yo({...n,processors:t});return T(e,r),So(r,e),ko(r,e)},jo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=yo({...i??{},target:a,io:t,processors:n});return T(e,o),So(o,e),ko(o,e)},Mo=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},No=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Po=(e,t)=>{Mo(e,`minimum`,t),No(e,`maximum`,t)},Fo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Io=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Lo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Ro=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},zo=(e,t)=>Mo(e,`minimum`,t.minimum),Bo=(e,t)=>No(e,`maximum`,t.maximum),Vo=e=>(t,n)=>{Ro(t,n.format);let[r,i]=e[n.format];Mo(t,`minimum`,r),No(t,`maximum`,i)},Ho={greater_than:(e,t)=>Mo(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>No(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Fo(e,t.value),number_format:Vo(Ye),bigint_format:Vo(Xe),min_length:zo,max_length:Bo,length_equals:(e,t)=>Po(e,t.length),min_size:zo,max_size:Bo,size_equals:(e,t)=>Po(e,t.size),string_format:(e,t)=>{Ro(e,t.format),t.pattern&&Io(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)=>Lo(e,t.mime)};function D(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Ho[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Mo(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Mo(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&No(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&No(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Fo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Lo(t,i.mime);for(let e of i.patterns??[])Io(t,e);return t}let Uo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Wo=/* @__PURE__ */ new Map([[Ur,Dn],[Gr,On]]),Go=e=>Wo.get(e)??e,Ko=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=D(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Uo[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(Go);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}))])}},qo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=D(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)):bo(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}))])}},Jo=(e,t,n,r)=>{n.type=`boolean`},Yo=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Xo=(e,t,n,r)=>{n.not={}},Zo=(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)},Qo=(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(bo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(bo(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}},$o=(e,t,n,r)=>{bo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},es=(e,t,n,r)=>{bo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ts=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=D(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=T(a.element,t,{...r,path:[...r.path,`items`]})};function ns(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?ns(t.out):t.type===`catch`?ns(t.innerType):e._zod.optin}let rs=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&bo(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,T(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`?ns(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=T(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},is=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>T(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},as=(e,t,n,r)=>{let i=e._zod.def,a=T(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=T(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},os=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>T(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?T(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?ns(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}=D(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function ss(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=ss(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=>ss(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`)?zn:Rn).source)),p}let cs=/* @__PURE__ */ new WeakMap;function ls(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 cs.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=ss(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 us=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=D(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=T(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ae(i.patternProperties,Go(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=T(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=cs.get(t);n||(n=[],cs.set(t,n),t.deferred.push(()=>ls(t))),n.push(e)}i.additionalProperties=T(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&ns(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))}},ds=(e,t,n,r)=>{let i=e._zod.def,a=T(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},fs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ps=Symbol();function ms(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(bo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),ps):JSON.parse(o)}let hs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=ms(i.defaultValue,e,t,n,r);o!==ps&&(n.default=o)},gs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=ms(i.defaultValue,e,t,n,r);o!==ps&&(n._prefault=o)},_s=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{bo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},vs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;T(o,t,r);let s=t.seen.get(e);s.ref=o},ys=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},bs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},xs=(e,t,n,r)=>{let i=e._zod.innerType;T(i,t,r);let a=t.seen.get(e);a.ref=i},Ss=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function Cs(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 O=/*@__PURE__*/ y(`ZodError`,(e,t)=>{Vt.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Ss.has(n)||(Ss.add(n),Cs(n,`format`,e=>t=>Wt(e,t)),Cs(n,`flatten`,e=>t=>Ut(e,t)),Cs(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),Cs(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}),ws=/* @__PURE__ */ Kt(O),Ts=/* @__PURE__ */ qt(O),Es=/* @__PURE__ */ Jt(O),Ds=/* @__PURE__ */ Xt(O),Os=/* @__PURE__ */ nn(O),ks=/* @__PURE__ */ rn(O),As=/* @__PURE__ */ an(O),js=/* @__PURE__ */ on(O),Ms=/* @__PURE__ */ sn(O),Ns=/* @__PURE__ */ cn(O),Ps=/* @__PURE__ */ ln(O),Fs=/* @__PURE__ */ un(O);function Is(){b.localeError||x(sa())}function Ls(){b.memoizer||x({memoizer:ia()})}let k=/*@__PURE__*/ y(`ZodType`,(e,t)=>(Is(),C.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(tl(e,t))},superRefine(e,t){return this.check(nl(e,t))},overwrite(e){return this.check(/* @__PURE__ */ oo(e))},optional(){return Pc(this)},exactOptional(){return Ic(this)},nullable(){return Rc(this)},nullish(){return Pc(Rc(this))},nonoptional(e){return Wc(this,e)},array(){return F(this)},or(e){return R([this,e])},and(e){return Tc(this,e)},transform(e){return Jc(this,Mc(e))},default(e){return Bc(this,e)},prefault(e){return Hc(this,e)},catch(e){return Kc(this,e)},pipe(e){return Jc(this,e)},readonly(){return Xc(this)},describe(e){let t=this.clone();return da.add(t,{description:e}),t},meta(...e){if(e.length===0)return da.get(this);let t=this.clone();return da.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`,{...dr(this),jsonSchema:{input:jo(this,`input`),output:jo(this,`output`)}})},set"~standard"(e){vt(this,`~standard`,e)},parse:function e(t,n){return ws(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ts(this,t,n,{callee:e})},safeParse(e,t){return Es(this,e,t)},async safeParseAsync(e,t){return Ds(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){vt(this,`spa`,e)},validate(e,t){return $t(this,e,t)},validateAsync(e,t){return tn(this,e,t)},encode:function e(t,n){return Os(this,t,n,{callee:e})},decode:function e(t,n){return ks(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await As(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await js(this,t,n,{callee:e})},safeEncode(e,t){return Ms(this,e,t)},safeDecode(e,t){return Ns(this,e,t)},async safeEncodeAsync(e,t){return Ps(this,e,t)},async safeDecodeAsync(e,t){return Fs(this,e,t)},toJSONSchema(e){return Ao(this,{})(e)},get description(){return da.get(this)?.description},get _def(){return this._zod.def}}),Rs=/*@__PURE__*/ y(`_ZodString`,(e,t)=>{fr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ko(e,t,n,r)},/*@__PURE__*/ bt({format:e=>D(e).format??null,minLength:e=>D(e).minimum??null,maxLength:e=>D(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ eo(...e))},includes(...e){return this.check(/* @__PURE__ */ ro(...e))},startsWith(...e){return this.check(/* @__PURE__ */ io(...e))},endsWith(...e){return this.check(/* @__PURE__ */ ao(...e))},min(...e){return this.check(/* @__PURE__ */ Qa(...e))},max(...e){return this.check(/* @__PURE__ */ Za(...e))},length(...e){return this.check(/* @__PURE__ */ $a(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Qa(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ to(e))},uppercase(e){return this.check(/* @__PURE__ */ no(e))},trim(){return this.check(/* @__PURE__ */ co())},normalize(...e){return this.check(/* @__PURE__ */ so(...e))},toLowerCase(){return this.check(/* @__PURE__ */ lo())},toUpperCase(){return this.check(/* @__PURE__ */ uo())},slugify(){return this.check(/* @__PURE__ */ fo())}})),zs=/*@__PURE__*/ y(`ZodString`,(e,t)=>{fr.init(e,t),Rs.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ma(Ws,e))},url(e){return this.check(/* @__PURE__ */ ba(Js,e))},jwt(e){return this.check(/* @__PURE__ */ Fa(uc,e))},emoji(e){return this.check(/* @__PURE__ */ xa(Xs,e))},guid(e){return this.check(/* @__PURE__ */ ha(Gs,e))},uuid(e){return this.check(/* @__PURE__ */ ga(Ks,e))},uuidv4(e){return this.check(/* @__PURE__ */ _a(Ks,e))},uuidv6(e){return this.check(/* @__PURE__ */ va(Ks,e))},uuidv7(e){return this.check(/* @__PURE__ */ ya(Ks,e))},nanoid(e){return this.check(/* @__PURE__ */ Sa(Zs,e))},cuid(e){return this.check(/* @__PURE__ */ Ca(Qs,e))},cuid2(e){return this.check(/* @__PURE__ */ wa($s,e))},ulid(e){return this.check(/* @__PURE__ */ Ta(ec,e))},base64(e){return this.check(/* @__PURE__ */ Ma(sc,e))},base64url(e){return this.check(/* @__PURE__ */ Na(cc,e))},xid(e){return this.check(/* @__PURE__ */ Ea(tc,e))},ksuid(e){return this.check(/* @__PURE__ */ Da(nc,e))},ipv4(e){return this.check(/* @__PURE__ */ Oa(rc,e))},ipv6(e){return this.check(/* @__PURE__ */ ka(ic,e))},cidrv4(e){return this.check(/* @__PURE__ */ Aa(ac,e))},cidrv6(e){return this.check(/* @__PURE__ */ ja(oc,e))},e164(e){return this.check(/* @__PURE__ */ Pa(lc,e))},datetime(e){return this.check(/* @__PURE__ */ Ia(Bs,e))},date(e){return this.check(/* @__PURE__ */ La(Vs,e))},time(e){return this.check(/* @__PURE__ */ Ra(Hs,e))},duration(e){return this.check(/* @__PURE__ */ za(Us,e))}});function A(e){return/* @__PURE__ */ pa(zs,e)}let j=/*@__PURE__*/ y(`ZodStringFormat`,(e,t)=>{w.init(e,t),Rs.init(e,t)}),Bs=/*@__PURE__*/ y(`ZodISODateTime`,(e,t)=>{jr.init(e,t),j.init(e,t)}),Vs=/*@__PURE__*/ y(`ZodISODate`,(e,t)=>{Mr.init(e,t),j.init(e,t)}),Hs=/*@__PURE__*/ y(`ZodISOTime`,(e,t)=>{Nr.init(e,t),j.init(e,t)}),Us=/*@__PURE__*/ y(`ZodISODuration`,(e,t)=>{Pr.init(e,t),j.init(e,t)}),Ws=/*@__PURE__*/ y(`ZodEmail`,(e,t)=>{hr.init(e,t),j.init(e,t)}),Gs=/*@__PURE__*/ y(`ZodGUID`,(e,t)=>{pr.init(e,t),j.init(e,t)}),Ks=/*@__PURE__*/ y(`ZodUUID`,(e,t)=>{mr.init(e,t),j.init(e,t)});function qs(e){return/* @__PURE__ */ ga(Ks,e)}let Js=/*@__PURE__*/ y(`ZodURL`,(e,t)=>{Cr.init(e,t),j.init(e,t)});function Ys(e){return/* @__PURE__ */ ba(Js,e)}let Xs=/*@__PURE__*/ y(`ZodEmoji`,(e,t)=>{wr.init(e,t),j.init(e,t)}),Zs=/*@__PURE__*/ y(`ZodNanoID`,(e,t)=>{Tr.init(e,t),j.init(e,t)}),Qs=/*@__PURE__*/ y(`ZodCUID`,(e,t)=>{Er.init(e,t),j.init(e,t)}),$s=/*@__PURE__*/ y(`ZodCUID2`,(e,t)=>{Dr.init(e,t),j.init(e,t)}),ec=/*@__PURE__*/ y(`ZodULID`,(e,t)=>{Or.init(e,t),j.init(e,t)}),tc=/*@__PURE__*/ y(`ZodXID`,(e,t)=>{kr.init(e,t),j.init(e,t)}),nc=/*@__PURE__*/ y(`ZodKSUID`,(e,t)=>{Ar.init(e,t),j.init(e,t)}),rc=/*@__PURE__*/ y(`ZodIPv4`,(e,t)=>{Fr.init(e,t),j.init(e,t)}),ic=/*@__PURE__*/ y(`ZodIPv6`,(e,t)=>{Rr.init(e,t),j.init(e,t)}),ac=/*@__PURE__*/ y(`ZodCIDRv4`,(e,t)=>{zr.init(e,t),j.init(e,t)}),oc=/*@__PURE__*/ y(`ZodCIDRv6`,(e,t)=>{Vr.init(e,t),j.init(e,t)}),sc=/*@__PURE__*/ y(`ZodBase64`,(e,t)=>{Wr.init(e,t),j.init(e,t)}),cc=/*@__PURE__*/ y(`ZodBase64URL`,(e,t)=>{qr.init(e,t),j.init(e,t)}),lc=/*@__PURE__*/ y(`ZodE164`,(e,t)=>{Jr.init(e,t),j.init(e,t)}),uc=/*@__PURE__*/ y(`ZodJWT`,(e,t)=>{Xr.init(e,t),j.init(e,t)}),dc=/*@__PURE__*/ y(`ZodNumber`,(e,t)=>{Zr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ bt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=D(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=D(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=D(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>D(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},min(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Ka(e,t))},lte(e,t){return this.check(/* @__PURE__ */ qa(e,t))},max(e,t){return this.check(/* @__PURE__ */ qa(e,t))},int(e){return this.check(N(e))},safe(e){return this.check(N(e))},positive(e){return this.check(/* @__PURE__ */ Ja(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Ya(0,e))},negative(e){return this.check(/* @__PURE__ */ Ka(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ qa(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},step(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},finite(){return this}}));function M(e){return/* @__PURE__ */ Ba(dc,e)}let fc=/*@__PURE__*/ y(`ZodNumberFormat`,(e,t)=>{Qr.init(e,t),dc.init(e,t)});function N(e){return/* @__PURE__ */ Va(fc,e)}let pc=/*@__PURE__*/ y(`ZodBoolean`,(e,t)=>{$r.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jo(e,t,n,r)});function P(e){return/* @__PURE__ */ Ha(pc,e)}let mc=/*@__PURE__*/ y(`ZodNull`,(e,t)=>{ei.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r)});function hc(e){return/* @__PURE__ */ Ua(mc,e)}let gc=/*@__PURE__*/ y(`ZodUnknown`,(e,t)=>{ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function _c(){return/* @__PURE__ */ Wa(gc)}let vc=/*@__PURE__*/ y(`ZodNever`,(e,t)=>{ni.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r)});function yc(e){return/* @__PURE__ */ Ga(vc,e)}let bc=/*@__PURE__*/ y(`ZodArray`,(e,t)=>{Ls(),oi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ Qa(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Qa(1,e))},max(e,t){return this.check(/* @__PURE__ */ Za(e,t))},length(e,t){return this.check(/* @__PURE__ */ $a(e,t))},unwrap(){return this.element}});function F(e,t){return/* @__PURE__ */ po(bc,e,t)}let xc=/*@__PURE__*/ y(`ZodObject`,(e,t)=>{Ls(),fi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),Et(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return V(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:_c()}))},loose(){return this.clone(h(this._zod.def,{catchall:_c()}))},strict(){return this.clone(h(this._zod.def,{catchall:yc()}))},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(Nc,this,e[0])},exactPartial(...e){return it(Fc,this,e[0],`exactPartial`)},required(...e){return at(Uc,this,e[0])}});function I(e,t){let n={type:`object`,shape:e??{},...g(t)};return new xc(n)}function L(e,t){return new xc({type:`object`,shape:e,catchall:yc(),...g(t)})}let Sc=/*@__PURE__*/ y(`ZodUnion`,(e,t)=>{mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.options=t.options});function R(e,t){return new Sc({type:`union`,options:e,...g(t)})}let Cc=/*@__PURE__*/ y(`ZodDiscriminatedUnion`,(e,t)=>{Sc.init(e,t),gi.init(e,t)});function z(e,t,n){return new Cc({type:`union`,options:t,discriminator:e,...g(n)})}let wc=/*@__PURE__*/ y(`ZodIntersection`,(e,t)=>{_i.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r)});function Tc(e,t){return new wc({type:`intersection`,left:e,right:t})}let Ec=/*@__PURE__*/ y(`ZodTuple`,(e,t)=>{Ls(),bi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(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 Nc({type:`optional`,innerType:e}))})}});function Dc(e,t,n){let r=t instanceof C;return new Ec({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let Oc=/*@__PURE__*/ y(`ZodRecord`,(e,t)=>{Ls(),wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>us(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function B(e,t,n){return!t||!t._zod?new Oc({type:`record`,keyType:A(),valueType:e,...g(t)}):new Oc({type:`record`,keyType:e,valueType:t,...g(n)})}let kc=/*@__PURE__*/ y(`ZodEnum`,(e,t)=>{Ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(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 kc({...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 kc({...t,checks:[],...g(r),entries:i})}});function V(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new kc({type:`enum`,entries:n,...g(t)})}let Ac=/*@__PURE__*/ y(`ZodLiteral`,(e,t)=>{Ei.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(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 H(e,t){return new Ac({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let jc=/*@__PURE__*/ y(`ZodTransform`,(e,t)=>{Ls(),Di.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(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 Mc(e){return new jc({type:`transform`,transform:e})}let Nc=/*@__PURE__*/ y(`ZodOptional`,(e,t)=>{ki.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e){return new Nc({type:`optional`,innerType:e})}let Fc=/*@__PURE__*/ y(`ZodExactOptional`,(e,t)=>{Ai.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e){return new Fc({type:`optional`,innerType:e})}let Lc=/*@__PURE__*/ y(`ZodNullable`,(e,t)=>{ji.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rc(e){return new Lc({type:`nullable`,innerType:e})}let zc=/*@__PURE__*/ y(`ZodDefault`,(e,t)=>{Mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bc(e,t){return new zc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Vc=/*@__PURE__*/ y(`ZodPrefault`,(e,t)=>{Pi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e,t){return new Vc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Uc=/*@__PURE__*/ y(`ZodNonOptional`,(e,t)=>{Fi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wc(e,t){return new Uc({type:`nonoptional`,innerType:e,...g(t)})}let Gc=/*@__PURE__*/ y(`ZodCatch`,(e,t)=>{Ri.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Kc(e,t){return new Gc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Dt(t)})}let qc=/*@__PURE__*/ y(`ZodPipe`,(e,t)=>{zi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.in=t.in,e.out=t.out});function Jc(e,t){return new qc({type:`pipe`,in:e,out:t})}let Yc=/*@__PURE__*/ y(`ZodReadonly`,(e,t)=>{Vi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xc(e){return new Yc({type:`readonly`,innerType:e})}let Zc=/*@__PURE__*/ y(`ZodLazy`,(e,t)=>{Ui.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Qc(e){return new Zc({type:`lazy`,getter:e})}let $c=/*@__PURE__*/ y(`ZodCustom`,(e,t)=>{Wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(e,t,n,r)});function el(e,t){return/* @__PURE__ */ mo($c,e??(()=>!0),t)}function tl(e,t={}){return/* @__PURE__ */ ho($c,e,t)}function nl(e,t){return/* @__PURE__ */ go(e,t)}function rl(e){return/* @__PURE__ */ Ia(Bs,e)}function il(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 al=R([A(),M(),P(),hc()]);function ol(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 sl=el(ol,{message:`JSON value must not contain circular references`}),cl=Qc(()=>R([al,F(cl),B(A(),cl)])),U=sl.pipe(cl);sl.pipe(F(cl));let ll=sl.pipe(B(A(),cl)),ul=L({code:A().min(1),message:A().min(1),retryable:P(),diagnostic:A().min(1).optional(),stage:A().min(1).optional(),durationMs:M().int().nonnegative().optional(),stderrTail:A().min(1).optional()}).superRefine(il([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),dl=A().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),fl=e=>A().min(1).max(e).refine(e=>e.trim().length>0),pl=B(dl,I({label:fl(256).optional(),description:fl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),ml=B(dl,fl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),hl=A().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),W=hl.brand(),G=hl.brand(),gl=hl.brand();hl.brand(),hl.brand();let _l=A().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),vl=_l.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),yl=I({modes:F(I({id:vl,label:_l.max(256),description:_l.max(1024).optional(),dangerous:P().optional(),localizations:pl.optional()}).strict()).min(1).max(32),defaultModeId:vl}).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`]})});I({threadId:G,permissionModeId:vl}).strict();let bl=A().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`});I({sourceThreadId:G,lastTurnId:gl.optional(),targetHarnessId:W,targetModel:bl.max(1024).optional(),targetThinkingOptionId:bl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).optional()}).strict();let xl=I({sourceThreadId:G,sourceHarnessId:W,sourceHarnessLabel:bl.max(256).optional(),sourceModel:bl.max(1024).optional(),targetHarnessId:W,targetHarnessLabel:bl.max(256).optional(),targetModel:bl.max(1024).optional(),totalTurns:M().int().min(1),boundaryTurnNumber:M().int().min(1),includedTurnNumbers:F(M().int().min(1)),omittedTurns:M().int().min(0),preview:A().max(32e3),createdAtMs:M().int().nonnegative()}).strict();I({threadId:G,handoff:xl}).strict();let K=M().int().safe().nonnegative(),Sl=M().finite().nonnegative(),Cl=M().finite().min(0).max(100),wl=I({version:R([H(3),H(4)]).optional(),requestId:A().min(1),turnId:A().min(1).max(1024),outputTokens:K,startedAtMs:K,completedAtMs:K}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Tl=I({version:R([H(2),H(3),H(4)]).optional(),value:Sl,turnId:A().min(1).max(1024),at:K}).strict();I({outputTimings:F(wl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Tl.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Tl.extend({value:K}).optional()}).strict();let El=e=>ml.refine(t=>Object.values(t).every(t=>t.length<=e)),Dl=I({composerIndicators:F(I({kind:H(`countdown`),id:A().min(1).max(64),expiresAtUnix:K,label:El(256).optional(),tooltip:El(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:K.optional(),cachedInputTokens:K.optional(),cacheWriteInputTokens:K.optional(),outputTokens:K.optional(),outputTokensPerSecond:Sl.optional(),sessionOutputTokensPerSecond:Sl.optional(),apiOutputTokensPerSecond:Sl.optional(),reasoningOutputTokens:K.optional(),totalTokens:K.optional(),totalCostUsd:Sl.optional(),totalCredits:Sl.optional(),contextUsagePercent:Sl.optional(),cacheHitRatePercent:Cl.optional(),contextWindowTokens:K.optional(),contextUsedTokens:K.optional(),planFiveHourUsedPercent:Cl.optional(),planFiveHourResetsAtUnix:K.optional(),planSevenDayUsedPercent:Cl.optional(),planSevenDayResetsAtUnix:K.optional(),sessionCacheHitRatePercent:Cl.optional(),timeToFirstOutputMs:K.optional(),latestRequestTimeToFirstOutputMs:K.optional(),costSource:V([`publicPrice`,`native`]).optional(),unpricedModels:F(A().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`]})}),Ol=M().finite().min(0).max(100),kl=V([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),Al=I({id:A().min(1).max(256),label:A().min(1).max(256),localizations:pl.optional()}).strict(),jl=I({product:A().min(1),periodType:kl.optional(),scope:Al.optional(),localizations:pl.optional(),used:M().finite().nonnegative().optional(),limit:M().finite().nonnegative().optional(),unit:A().min(1).max(32).optional(),usagePercent:Ol,resetsAt:A().min(1).optional()}).strict(),Ml=I({availableCount:M().int().safe().positive(),nextExpiresAt:A().min(1).optional(),expiresAt:F(A().min(1)).min(1).max(32).optional()}).strict(),Nl=I({used:M().finite().nonnegative().optional(),limit:M().finite().nonnegative().optional(),unit:A().min(1).max(32).optional(),label:A().min(1).optional(),scope:Al.optional(),localizations:pl.optional(),usedPercent:Ol,resetsAt:A().min(1).optional(),periodType:kl,productUsage:F(jl).min(1).optional(),resetCredits:Ml.optional()}).strict(),Pl=I({amount:M().finite().nonnegative(),currency:A().trim().min(1).max(8),label:A().trim().min(1).max(128).optional()}).strict();I({threadId:G,refresh:H(`exact`).optional()}).strict(),I({threadId:G,usage:Dl.nullable(),accountCredits:Nl.optional(),accountBalance:Pl.optional(),accountCreditsSupported:P().optional()}).strict();let Fl=A().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Il=A().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Ll=V([`priority`,`ultrafast`]),q=I({id:Il,serviceTier:Ll.optional()}).strict();function Rl(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let J=Fl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),zl=Fl.max(256),Bl=I({id:J,label:Fl.max(256)}).strict(),Vl=I({ref:q,label:Fl.max(256),resolvedModelLabel:zl.optional(),fastModel:q.optional(),supportedThinkingOptionIds:F(J).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 Hl(e,t){if(t)return e?.models.find(e=>Rl(e.ref,t)||Rl(e.fastModel,t))}let Ul=F(Bl).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)}),Wl=I({models:F(Vl),defaultModel:q.optional(),thinkingOptions:Ul,defaultThinkingOptionId:J.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=>Rl(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=>Rl(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&&!Hl(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`]})}),Gl=I({fork:P(),forkAcrossCwd:P(),rollbackLastTurn:P()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Kl=V([`live`,`atCreate`]),ql=I({configuration:I({selectModel:P(),selectThinkingOption:P(),selectPermissionMode:P(),permissionModeScope:Kl.default(`live`)}).strict(),history:Gl,subagents:I({observe:P(),readTranscript:P()}).strict().optional(),autonomousTurns:I({observe:P()}).strict().optional(),steer:P().optional(),persistentPlan:P().optional()}).strict();I({effectiveModel:q.optional(),resolvedModelLabel:zl.optional(),effectiveThinkingOptionId:J.optional(),availableThinkingOptions:Ul.optional(),effectivePermissionModeId:vl.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 Jl=I({open:H(!0)}).strict();R([I({status:H(`ready`),catalog:Wl,permissionModes:yl.optional(),capabilities:ql,webUi:Jl.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`]})}),I({status:V([`notInstalled`,`unavailable`,`error`]),error:ul}).strict()]),I({harnessId:W,cwd:Fl.max(16384).optional(),refresh:P().optional(),purpose:H(`availability`).optional(),credentialAccess:V([`allow`,`retry`]).optional()}).strict(),I({harnessId:W}).strict(),I({}).strict(),I({threadId:G,model:q}).strict(),I({threadId:G,thinkingOptionId:J}).strict(),I({threadId:G,includeReferenceCapability:P().optional()}).strict(),z(`owner`,[I({owner:H(`codex`),locked:P(),effectiveModel:q.optional(),resolvedModelLabel:zl.optional(),effectiveThinkingOptionId:J.optional(),effectivePermissionModeId:vl.optional(),history:Gl.optional(),supportsThreadReferences:H(!0).optional(),handoff:xl.optional()}).strict(),I({owner:H(`external`),harnessId:Fl.max(256),transportModelId:Fl.max(8192),effectiveModel:q.optional(),resolvedModelLabel:zl.optional(),effectiveThinkingOptionId:J.optional(),availableThinkingOptions:Ul.optional(),effectivePermissionModeId:vl.optional(),catalog:Wl.optional(),history:Gl,usage:Dl.optional(),handoff:xl.optional(),locked:H(!0)}).strict()]),I({threadIds:F(G).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 Yl=z(`owner`,[I({threadId:G,owner:H(`codex`)}).strict(),I({threadId:G,owner:H(`external`),harnessId:A().max(256).pipe(W)}).strict()]);I({threads:F(Yl).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)}),I({threadId:G,text:A().optional()}).strict(),I({kind:H(`application`),value:A().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),kt}}).pipe(I({expectedTurnId:gl,clientUserMessageId:A().min(1),delivery:V([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),V([`activeTurn`,`newTurn`]),I({delivery:V([`official`,`activeTurn`,`newTurn`])}).strict();let Xl=A().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),Zl=Xl.pipe(W),Ql=Zl.refine(e=>e!==`codex`,`The official Codex identity is reserved`),$l=A().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`),eu=Ys().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),tu=I({en:A().max(4096),"zh-CN":A().max(4096).optional()}).strict(),nu=I({commands:F(I({terminal:A().max(256),command:A().max(4096)}).strict()).max(8),before:tu.optional(),after:tu.optional(),downloads:F(I({label:A().max(128),url:eu}).strict()).max(8).optional()}).strict(),ru={id:Zl,name:A().trim().min(1).max(128),version:A().min(1).max(128),kind:H(`usage`).optional(),iconStyle:I({vector:I({viewBox:A().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:A().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:F(I({d:A().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:V([`evenodd`,`nonzero`]).optional(),fill:A().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:A().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:M().min(0).max(50).optional(),paddingRatio:M().min(0).max(.25).optional()}).strict().optional(),installation:nu.optional(),notice:tu.optional(),launchCommand:H(!0).optional(),links:I({website:eu.optional(),documentation:eu.optional(),installation:eu.optional()}).strict().optional()};I({manifestVersion:H(1),...ru,adapterApiVersion:M().int().positive(),entry:$l,icon:$l.optional()}).strict();let iu=A().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),au=I({...ru,icon:iu.optional()}).strict();I({}).strict(),I({plugins:F(au.extend({id:Ql})).max(128)}).strict(),I({version:H(1),enabled:F(Zl).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let ou=Xl,su=V([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),cu=V([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),lu=A().trim().min(1).max(128);function uu(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 du=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),fu=$l.refine(e=>uu(e)!==void 0&&du(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),pu=A().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Ys({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 mu(e){return L({en:e,"zh-CN":e})}let hu=mu(A().trim().min(1)),gu=F(cu).max(cu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),_u=F(su).max(su.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),vu={key:A().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:hu,description:hu.optional()},yu={...vu,step:M().positive().optional(),default:M().optional()},bu=L({value:A(),label:hu}),xu=z(`type`,[L({...vu,type:H(`boolean`),default:P().optional()}),L({...vu,type:H(`string`),placeholder:hu.optional(),default:A().optional()}),L({...yu,type:H(`number`),min:M().optional(),max:M().optional()}),L({...yu,type:H(`range`),min:M(),max:M()}),L({...vu,type:H(`select`),options:F(bu).min(1),default:A().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`)}}),Su=I({manifestVersion:N().positive(),id:ou,name:R([lu,mu(lu)]),version:A().min(1).max(128),desktopApi:N().positive()}).passthrough().extend({manifestVersion:H(1),desktopApi:H(1),description:L({en:A().max(4096),"zh-CN":A().max(4096).optional()}).optional(),author:A().trim().min(1).max(128).optional(),repository:pu.optional(),details:L({en:A().max(16384),"zh-CN":A().max(16384).optional()}).optional(),icon:fu.optional(),screenshots:F(fu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:L({script:$l,style:$l.optional()}).optional(),backend:L({script:$l.refine(du)}).optional(),slots:_u.default(()=>[]),settingsSchema:F(xu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:gu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),Cu=A().regex(/^[a-f0-9]{64}$/u),wu=L({state:V([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:Cu.optional(),error:A().optional(),conflictWith:ou.optional()});L({controllerPid:N().positive(),targetId:A().nullable(),updatedAt:rl(),handledReloadToken:qs().optional(),extensions:B(A(),wu),surfaces:B(A(),wu).optional()});let Tu=V([`official`,`community`]);function Eu(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Du=pu.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||Eu(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`),Ou=L({id:ou,version:A().trim().min(1).max(128),name:hu.extend({en:lu,"zh-CN":lu}),description:mu(A().trim().min(1).max(4096)),details:mu(A().trim().min(1).max(16384)).optional(),author:A().trim().min(1).max(128),repository:pu,stars:M().int().min(0).optional(),downloads:M().int().min(0).optional(),categories:gu.optional(),trustTier:Tu.default(`community`),icon:pu.optional(),screenshots:F(pu).max(4).optional(),downloadUrl:Du,sha256:Cu,slots:_u.optional(),publishedAt:A().optional(),updatedAt:A().optional(),minCodexHostVersion:A().optional()});L({schemaVersion:H(1),generatedAt:A(),extensions:F(Ou).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let ku=A().trim().min(1).max(128),Au=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,ju=ou.refine(e=>!Au.test(e),`Reserved extension ID`),Mu=V([`desktop`,`web`]),Nu=Cu,Pu=qs(),Fu=$l.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Au.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),Iu=Su.shape,Lu=(e,t=0)=>L({en:A().trim().min(t).max(e),"zh-CN":A().trim().min(t).max(e)}),Ru=e=>Fu.refine(t=>t.endsWith(e),`Expected a ${e} file`),zu=Ru(`.mjs`),Bu=Ru(`.css`).optional(),Vu=e=>e.normalize(`NFC`).toLowerCase(),Hu=L({manifestVersion:H(2),id:ju,name:Lu(128,1),version:A().trim().min(1).max(128),description:Lu(4096),details:Lu(16384).optional(),author:Iu.author,repository:Iu.repository,icon:Iu.icon.refine(e=>e===void 0||Fu.safeParse(e).success),screenshots:Iu.screenshots.refine(e=>e===void 0||e.every(e=>Fu.safeParse(e).success)),categories:Iu.categories,settingsSchema:Iu.settingsSchema,slots:Iu.slots.removeDefault().optional(),page:L({apiVersion:H(1),entry:zu,style:Bu,title:Lu(128,1).optional()}).optional(),widget:L({apiVersion:H(1),entry:zu,style:Bu}).optional(),desktop:L({apiVersion:H(1),script:Ru(`.js`),style:Bu}).optional(),web:L({apiVersion:H(1),entry:zu.optional(),style:Bu}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:L({apiVersion:H(1),entry:zu}).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||Vu(e)!==Vu(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Uu({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 Wu=ku,Gu=N().nonnegative(),Ku=L({revision:Gu,enabled:F(ju).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)}),{downloadUrl:qu,...Ju}=Ou.shape,Yu=I({...Ju,id:ju,format:H(`codexhost`),targets:F(Mu).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:L({page:N().positive().optional(),widget:N().positive().optional(),desktop:N().positive().optional(),web:N().positive().optional(),backend:N().positive().optional()}),downloadUrl:qu.refine(e=>e.startsWith(`https://`),`Expected HTTPS`)}).refine(({targets:e,apis:t})=>{let n=Uu({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`);I({schemaVersion:H(2),generatedAt:A().min(1),extensions:F(Yu).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:pu,fetchedAt:rl(),cached:P()});let Xu={id:ju},Zu={...Xu,activationId:Pu,digest:Nu},Qu={...Xu,activationId:Zu.activationId.optional()},$u=A().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`),ed=A().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function td(e){return A().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 nd=L({type:H(`github`),repository:A().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:ed.optional(),tag:ed.optional(),asset:A().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Fu.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),rd=R([L({type:H(`catalog`),...Xu}),nd,L({type:H(`zip`),base64:td(67108864).min(4)}),L({type:H(`zip`),localZipPath:$u}),L({type:H(`localDir`),localDir:$u})]),id=z(`type`,[L({type:H(`catalog`),...Xu}),nd,L({type:H(`zip`)}),L({type:H(`localDir`)})]),ad=L({...Zu,manifest:Hu,installedAt:rl(),source:id.optional()}),od=e=>A().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),sd={desktopConflictWith:ju.optional()},cd=V([`none`,`inactive`,`starting`,`running`,`failed`]),ld=z(`state`,[ad.extend({state:H(`valid`),enabled:P(),...sd,iconDataUrl:od(131072).optional(),screenshotDataUrls:F(od(524288)).max(4).optional(),backendState:cd.optional(),backendError:A().optional()}),L({state:V([`invalid`,`incompatible`]),id:A().min(1),enabled:P(),error:A()})]);L({revision:Gu,configuration:Ku,diagnostics:F(A()),extensions:F(ld)}),L({revision:Gu,extensions:F(ad.extend({...sd,settingsRevision:Gu})).max(64)});let Y={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`},ud=Object.freeze(Object.values(Y));new Set(ud),L({});let dd={expectedRevision:Gu};L({...Xu,...dd}),ad.extend({replaced:P()}),z(`state`,[L({state:H(`saved`),configuration:Ku}),L({state:H(`revision-conflict`),revision:Gu})]),L({...Qu,digest:Zu.digest.optional(),path:Fu}),L({mimeType:A().min(1),base64:td(16777216),digest:Zu.digest}),L({settingsRevision:Gu,values:ll}),Y.list,Y.snapshot,Y.catalog,L({forceRefresh:P().optional()}),Y.install,L({source:rd}),Y.update,L({...Xu,expectedDigest:Zu.digest,expectedActivationId:Zu.activationId.optional(),source:rd.optional()}),Y.enable,Y.disable,Y.uninstall,L({...Xu,removeData:P().optional(),expectedDigest:Zu.digest.optional()}),L({...Xu,removed:P()}),Y.recover,L({expectedRevision:dd.expectedRevision.optional()}),Y.asset,Y.settingsGet,L(Qu),Y.settingsSet,L({...Qu,expectedSettingsRevision:Gu,values:ll}),Y.backendInvoke,L({...Qu,method:Wu,params:U.optional()}),L({result:U}),I({threadId:G}).strict(),I({confirmed:P()}).strict(),[...ud],I({sections:F(I({id:A().min(1),name:A().min(1),threads:F(ll)}).strict())}).strict(),I({threadId:A().min(1).max(1024),sectionId:A().min(1).max(1024).nullable()}).strict(),I({threadIds:F(A().min(1))}).strict(),I({threadId:A().min(1).max(1024),pinned:P()}).strict(),I({}).strict(),I({parents:B(A().min(1),A().min(1))}).strict(),I({prompt:A().max(16384).optional()}).strict(),I({projects:F(I({id:A(),name:A(),rootPaths:F(A())})),nativeProjects:H(!0).optional(),assignments:B(A(),A()),projectless:F(A()),pinned:F(A()),sectionProjects:B(A(),F(A())).optional()});let fd=B(A(),_c()),pd=I({epoch:A().uuid(),sequence:M().int().nonnegative()});z(`type`,[I({type:H(`projects-changed`),cursor:pd}),I({type:H(`skills-changed`),cursor:pd,cwd:A().optional()}),I({type:H(`harness-inspection-changed`),cursor:pd,harnessId:A().min(1)}),I({type:H(`display-settings-changed`),cursor:pd}),I({type:H(`preferences-changed`),cursor:pd,revision:M().int().nonnegative()}),I({type:H(`extensions-changed`),cursor:pd,revision:Gu}),I({type:H(`hello`),version:H(1),cursor:pd,reset:P()}),I({type:H(`changed`),cursor:pd,threadId:A().min(1),method:A().min(1)})]);let md=z(`type`,[I({type:H(`text`),id:A(),prompt:A(),secret:P().optional(),optional:P().optional()}),I({type:H(`choice`),id:A(),prompt:A(),multiple:P(),allowOther:P(),optional:P().optional(),options:F(I({value:A(),label:A(),description:A().optional()}))})]),hd=z(`type`,[I({type:H(`approval`),title:A(),description:A().optional(),subject:_c().optional(),actions:F(I({id:A(),label:A(),effect:A()}))}),I({type:H(`question`),title:A().optional(),questions:F(md)})]),gd=I({requestId:R([A(),M().int()]),threadId:A(),kind:V([`approval`,`question`]),interaction:hd,request:fd}),_d=I({id:A().min(1),clientUserMessageId:A().min(1),input:F(fd),presentationInput:F(fd).nullable().optional()}).passthrough();I({fields:F(I({path:F(R([A(),M().int().nonnegative()])),originalLength:M().int().nonnegative()}))});let vd=I({id:A().min(1),status:A().min(1),codexhostTurnOutcome:I({status:H(`unknown`),reason:A()}).optional(),items:F(I({id:A().min(1),type:A().min(1)}).passthrough()),codexhostFileOperations:F(I({beforeItemId:A().nullable(),item:I({id:A().min(1),type:A().min(1)}).passthrough()})).optional(),error:I({message:A().optional()}).passthrough().nullable().optional(),fingerprint:A().min(1).optional(),unchanged:H(!0).optional()}).passthrough(),yd=I({id:A().min(1).max(512),fingerprint:A().min(1).max(128)});I({threadId:A().min(1),knownTurns:F(yd).max(64).optional(),truncateToolOutput:P().optional()});let bd=I({harnessId:A().min(1),nativeSessionId:A().min(1)});I({cursor:pd,activeTurnId:A().min(1).nullable().optional(),command:I({name:A().min(1),turn:vd,subsequentTurnId:A().min(1).optional()}).optional(),thread:I({id:A().min(1),cwd:A(),modelProvider:A().min(1),createdAt:M(),updatedAt:M(),status:I({type:A()}).passthrough(),name:A().nullable().optional(),preview:A().optional(),codexhostImportSource:bd.optional(),turns:F(vd).length(0)}).passthrough(),turnsPage:I({data:F(vd).max(5),nextCursor:A().nullable()}),configuration:I({native:I({model:A().min(1).max(1024).optional(),reasoningEffort:A().min(1).max(128).optional()}).optional(),effectiveModel:q.optional(),effectiveThinkingOptionId:J.optional(),effectivePermissionModeId:vl.optional()}),queue:I({items:F(_d),pausedReason:V([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:F(gd),handoff:xl.optional()}),I({version:H(1),owner:H(`service`).optional(),pid:M().int().positive(),port:M().int().min(1).max(65535),token:A().regex(/^[0-9a-f]{64}$/u),startedAt:M(),epoch:A().uuid(),capabilities:I({peerDelegation:H(1).optional()}).optional()}),I({epoch:A().uuid(),threadId:A().min(1),requestId:R([A(),M().int()]),result:fd}),I({includeArchived:P().optional(),officialCursor:I({live:A().nullable(),archived:A().nullable().optional()}).strict().optional(),scope:R([I({cwd:A().min(1).max(4096),excludeCwds:F(A().min(1).max(4096)).max(1024)}).strict(),I({projectId:A().min(1).max(1024),legacyThreadIds:F(A().min(1).max(1024)).max(1024),rootPaths:F(A().min(1).max(4096)).max(1024).optional()}).strict()]).optional()}).strict(),I({threads:F(ll),ownership:F(Yl),archivedThreadIds:F(G),officialCursor:I({live:A().nullable(),archived:A().nullable().optional()}).strict().optional()}).strict();let xd=V([`running`,`waiting`,`idle`,`unknown`]),Sd=L({harnessId:W,title:A().optional(),status:xd,archived:P()}),Cd=L({revision:N().nonnegative(),parents:B(G,G),nodes:B(G,Sd),truncated:P()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,nodes:t})=>Object.entries(e).every(([e,n])=>Object.hasOwn(t,e)&&Object.hasOwn(t,n)),`Missing Thread tree node`),wd=A().min(1).max(128);L({});let Td=L({subscriptionId:wd});L({}),Td.extend({snapshot:Cd});let Ed=A().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);I({available:P()}).strict(),I({path:A().min(1),mimeType:Ed}).strict();let Dd=V([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);z(`ok`,[I({ok:H(!0),text:A()}).strict(),I({ok:H(!1),error:I({code:Dd}).strict()}).strict()]),I({threadId:G.optional(),cwd:A().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Od=I({name:A().min(1).regex(/^[^\s[\]]+$/u),description:A().optional(),path:A().min(1),scope:V([`project`,`global`]),source:A().min(1)}).strict();I({revision:M().int().nonnegative(),complete:P(),skills:F(Od),warnings:F(A()).optional()}).strict(),I({cwd:A().min(1).optional()}).strict();let kd=I({kind:V([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:A().min(1)}).strict(),Ad=z(`status`,[I({status:H(`not-installed`)}),I({status:H(`not-running`)}),I({status:H(`not-logged-in`)}),I({status:H(`https-disabled`)}),I({status:H(`not-serving`),command:A()}),I({status:H(`occupied`),target:A()}),I({status:H(`serving`),url:A(),funnel:P()}),I({status:H(`error`),message:A()})]);I({state:Ad,error:A().optional()}).strict();let jd=z(`status`,[I({status:H(`on`)}),I({status:H(`off`)}),I({status:H(`invalid`),reason:A()})]),Md=I({lan:P(),autostart:jd}).strict(),Nd=I({expiresAt:A().optional(),issuing:P(),failure:I({detail:A().optional(),retryAt:A(),paused:P()}).optional()}),Pd=z(`status`,[I({status:H(`off`),reason:V([`invite`,`name-taken`,`banned`]).optional()}),I({status:H(`connecting`),reason:V([`full`,`unreachable`]).optional()}),I({status:H(`connected`),url:A(),certificate:Nd}),I({status:H(`missing-certificate`),url:A(),certificate:Nd}),I({status:H(`stopped`),reason:V([`replaced`,`rejected`,`unsupported-version`])})]);A().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()),A().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let Fd=V([`official`,`self-hosted`]);I({secret:A().min(1),lastUsedAt:M().nullable(),networkUrls:F(kd),directCandidates:F(kd).optional(),tailscale:Ad,background:Md.optional(),relay:I({state:Pd,enabled:P(),kind:Fd,officialHost:A(),customHost:A().optional(),officialHostname:A().optional(),customHostname:A().optional(),quotaUntil:A().optional()}).strict().optional()}).strict();let Id=L({threadId:A().min(1).max(1024),view:V([`result`,`messages`]),from:M().int().min(1).max(2**53-1).optional(),to:M().int().min(1).max(2**53-1).optional()}),Ld=A().regex(/^[a-zA-Z0-9_-]{1,64}$/u),Rd=A().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),zd=V([`relay`,`tailscale`,`lan`,`custom`]),Bd=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],Vd=V(Bd);new Set(Bd);let Hd=V([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]);I({peers:F(I({peerId:Ld,hostId:Rd,name:A().min(1).max(120),color:Vd.optional(),origin:A().min(1).max(2048),transportKind:zd,encrypted:P(),enabled:P(),state:Hd,latencyMs:M().int().nonnegative().optional(),version:A().max(128).optional(),platform:A().max(64).optional(),hostname:A().max(255).optional(),homeDir:A().max(4096).optional(),lastError:A().max(1e3).optional(),projectCount:M().int().nonnegative(),createdAt:A(),updatedAt:A()}))}),I({connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional(),name:A().trim().min(1).max(120).optional(),color:Vd.optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),I({peerId:Ld,name:A().trim().min(1).max(120).optional(),color:Vd.nullable().optional(),connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional(),enabled:P().optional()}),I({peerId:Ld}),I({removed:P()}),I({peerId:Ld.optional(),connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let Ud=I({id:A().min(1).max(1024),name:A().min(1).max(512),path:A().min(1).max(8192)});I({ok:P(),latencyMs:M().int().nonnegative().optional(),origin:A().max(2048).optional(),transportKind:zd.optional(),encrypted:P().optional(),version:A().max(128).optional(),platform:A().max(64).optional(),hostname:A().max(255).optional(),homeDir:A().max(4096).optional(),projectCount:M().int().nonnegative().optional(),projects:F(Ud).optional(),error:A().max(1e3).optional()});let Wd=I({id:A().min(1).max(1024),name:A().min(1).max(512),path:A().min(1).max(8192),threadIds:F(A().min(1).max(1024))}),Gd=I({attachments:H(1).optional(),workspaceFiles:H(1).optional(),officePreview:H(1).optional(),delegation:H(1).optional()}),Kd=I({version:A().max(128),platform:A().max(64),hostname:A().max(255),homeDir:A().max(4096).optional(),epoch:A().min(1).max(256),projects:F(Wd),capabilities:Gd.optional()});L({threadId:A().min(1).max(1024),scope:A().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:A().min(1).max(256).optional(),mode:V([`queue`,`steer`]).optional(),expectedTurnId:A().min(1).max(1024).nullable().optional(),content:F(z(`type`,[L({type:H(`text`),text:A()}),L({type:H(`file`),receiptId:A().min(1).max(128)})])).min(1).max(64)});let qd=I({ok:H(!1),error:I({code:A(),message:A(),details:B(A(),_c()).optional()})});R([I({ok:H(!0),value:I({receiptId:A().min(1),file:I({attachmentId:A(),name:A(),bytes:M().int().nonnegative()})})}),qd]),R([I({ok:H(!0),value:I({accepted:H(!0)})}),qd]);let Jd=I({name:A().min(1).max(512),path:A().min(1).max(8192),kind:H(`directory`)});I({peerId:Ld,path:A().min(1).max(8192).optional()}),I({path:A().min(1).max(8192),parentPath:A().min(1).max(8192).nullable(),homeDir:A().min(1).max(8192).optional(),entries:F(Jd)}),I({peerId:Ld,parentPath:A().min(1).max(8192),name:A().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),I({path:A().min(1).max(8192),name:A().min(1).max(255)}),I({peerId:Ld,path:A().min(1).max(8192),title:A().trim().min(1).max(255).optional()}),I({peerId:Ld,workspaceId:A().min(1).max(1024),title:A().trim().min(1).max(255)}),I({peerId:Ld,workspaceId:A().min(1).max(1024)}),I({workspaceId:A().min(1).max(1024).optional(),manifest:Kd});let Yd=V([`listHarnesses`,`inspect`,`start`,`send`,`cancel`,`read`,`answer`,`list`]);L({operation:Yd,hopCount:M().int().min(0).max(16),sourceId:Ld.optional(),input:ll});let Xd=L({code:A().min(1).max(128),message:A().max(4096),details:ll.optional()});R([L({ok:H(!0),value:U}),L({ok:H(!1),error:Xd})]);let Zd=L({id:A().min(1).max(1024),name:A().min(1).max(512),path:A().min(1).max(8192)});L({hosts:F(L({hostId:Rd,displayName:A().min(1).max(120),online:P(),state:Hd,delegation:P(),projects:F(Zd),platform:A().max(64).optional(),hostname:A().max(255).optional(),homeDir:A().max(4096).optional()}))}),L({version:H(1),instanceId:A().min(1).max(128),pid:M().int().positive(),endpoint:A().min(1).max(256),token:A().regex(/^[0-9a-f]{64}$/u),startedAt:M().int().nonnegative()}),R([L({operation:H(`hosts`)}),L({operation:Yd,hostId:Rd,hopCount:M().int().min(0).max(16),timeoutMs:M().int().min(1).max(12e4).optional(),input:ll})]);let Qd=I({id:A().min(1).max(256),harnessId:A().min(1),label:A().min(1).max(512),provider:V([`openai-codex`,`xai`])}).strict(),$d=A().regex(/^[a-z][a-z0-9-]{0,47}$/),ef=I({name:$d,source:Qd,importedAt:A()}).strict(),tf=z(`action`,[I({action:H(`list`)}).strict(),I({action:H(`import`),sourceId:A().min(1).max(256),name:$d,confirmed:H(!0)}).strict(),I({action:H(`reimport`),sourceId:A().min(1).max(256),name:$d,confirmed:H(!0)}).strict(),I({action:H(`remove`),name:$d,confirmed:H(!0)}).strict()]),nf=I({provider:A().min(1).max(128),type:V([`oauth`,`api_key`,`unknown`]),label:A().min(1).max(512).optional(),vendor:V([`openai-codex`,`xai`]).optional()}).strict();I({sources:F(Qd),targets:F(I({harnessId:A(),providers:F(V([`openai-codex`,`xai`])),imports:F(ef),others:F(nf).default([])}).strict())}).strict(),I({targetHarnessId:A().min(1).max(128).optional(),request:tf}).strict(),I({events:P()});let rf=F(L({agent:A().min(1).max(128),section:V([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);L({entries:rf.nullable()}),L({}),L({entries:rf,initializeOnly:P().optional()});let af=L({enabled:P(),timeoutMinutes:M().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let of=A().regex(/^external$/u),sf=W.transform(e=>String(e)),cf=L({model:q.optional(),thinkingOptionId:J.optional(),permissionModeId:vl.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),lf=L({lastHarness:W.optional(),byHarness:B(sf,cf)}),uf=L({model:q.optional(),thinkingOptionId:J.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),df=L({byHarness:B(sf,uf)}),ff=A().min(1).max(1024),pf=L({idleRelease:af.optional(),favorites:B(sf,F(ff).max(2048)).default({}),newThread:lf.optional(),delegation:df.optional()});L({scope:of,revision:M().int().nonnegative(),values:pf}),L({scope:of.default(`external`)});let mf=z(`kind`,[L({kind:H(`idleRelease`),value:af}),L({kind:H(`favorite`),harnessId:W,modelId:ff,enabled:P()}),L({kind:H(`favorites`),harnessId:W,modelIds:F(ff).max(2048)}),L({kind:H(`newThread`),lastHarness:W.optional(),harnessId:W.optional(),configuration:cf.optional()}),L({kind:H(`delegation`),harnessId:W,configuration:uf.nullable()})]);L({scope:of.default(`external`),operations:F(mf).min(1).max(256),initializeOnly:P().optional(),expectedRevision:M().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`})}),L({version:H(1),revision:M().int().nonnegative(),scopes:B(of,pf)});let hf=M().finite().nonnegative(),gf=L({input:hf,output:hf,cacheRead:hf.optional(),cacheWrite:hf.optional(),cacheWrite1h:hf.optional()}),_f=A().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);L({path:A(),entries:F(L({key:A(),price:gf})),error:A().nullable()}),L({}),L({key:_f,price:gf.nullable(),previousKey:_f.optional()}),L({model:_f});let vf=L({official:P().optional(),canonicalModelId:A().min(1).optional(),provider:A().min(1).max(512),model:A().min(1).max(512),price:gf});L({price:gf.nullable(),suggestions:F(vf).max(6).optional()});let yf=[`today`,`7d`,`30d`,`90d`,`all`],X=M().int().min(0).max(2**53-1),bf=A().regex(/^\d{4}-\d{2}-\d{2}$/u),xf=A().min(1).max(128),Sf=A().min(1).max(512),Cf=A().min(1).max(4096);L({range:V(yf),timeZone:A().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:xf.optional(),model:Sf.nullable().optional(),project:Cf.nullable().optional(),date:bf.optional()});let wf=L({requests:X,inputTokens:X,cachedInputTokens:X,cacheWriteInputTokens:X,cacheKnownInputTokens:X,cacheHitCachedInputTokens:X,cacheHitInputTokens:X,outputTokens:X,reasoningOutputTokens:X,costUsd:M().finite().min(0),unpricedRequests:X,unmeteredRequests:X}),Tf=wf.shape,Ef=L({harness:xf,sessionId:A().min(1).max(512),project:Cf.nullable(),title:A().min(1).max(200).optional(),models:F(Sf).max(16),firstAtMs:X,lastAtMs:X,...Tf});L({range:V(yf),from:bf.nullable(),to:bf,filters:L({harness:xf.nullable(),model:Sf.nullable(),unknownModel:P(),project:Cf.nullable(),unknownProject:P(),date:bf.nullable()}),reading:L({complete:P(),sources:X,read:X}),failures:F(L({harness:xf,message:A().max(2048)})).max(256),options:L({harnesses:F(xf).max(256),models:F(Sf.nullable()).max(4096),projects:F(Cf.nullable()).max(4096)}),modelLabels:F(L({harness:xf,model:Sf,label:Sf})).max(4096).optional(),credits:F(L({harness:xf,model:Sf.nullable(),credits:M().finite().min(0),reportedRequests:X,requests:X})).max(4096).optional(),totals:wf,daily:F(L({date:bf,harness:xf,...Tf})).max(2e5),hourly:F(L({weekday:M().int().min(0).max(6),hour:M().int().min(0).max(23),...Tf})).max(168),byHarness:F(L({harness:xf,...Tf})).max(256),byModel:F(L({model:Sf.nullable(),...Tf,harnessPricedRequests:X})).max(4096),byProject:F(L({project:Cf.nullable(),...Tf})).max(4096),sessions:F(Ef).max(100),recentSessions:F(Ef).max(100).optional()}),I({threadId:G}),I({discarded:P()});let Df=z(`type`,[I({id:A().min(1),type:H(`choice`),prompt:A(),options:F(I({value:A().min(1),label:A(),description:A().optional()})).min(1),multiple:P(),allowOther:P(),optional:P()}),I({id:A().min(1),type:H(`text`),prompt:A(),multiline:P(),secret:H(!1),optional:P(),placeholder:A().optional(),prefill:A().optional()})]),Of=I({interactionId:A().min(1),turnId:A().min(1),title:A().optional(),questions:F(Df).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});L({threadId:A().min(1)}),I({questions:F(Of)}),L({threadId:A().min(1),turnId:A().min(1),interactionId:A().min(1),answers:B(A(),F(A())),cancelled:P().default(!1)}),I({accepted:H(!0)});let kf=`codexhostActiveTurnId`,Af=/* @__PURE__ */ new Set([kf,`codexhostTurnChanges`,`codexhostToolOutput`]),jf=I({path:A(),oldText:A().nullable(),newText:A()});I({sessionId:A().min(1),turn:M().int().nonnegative(),path:A().min(1).optional()}),I({diffs:F(jf)}),L({}),L({}),I({reference:I({sessionId:A().min(1),epoch:A().min(1),turn:M().int().nonnegative(),seq:M().int().nonnegative(),callId:A().min(1),part:M().int().nonnegative(),version:A().min(1)}),length:M().int().nonnegative(),bytes:M().int().nonnegative()}),L({title:A().trim().min(1).max(200),type:V([`info`,`warning`,`danger`]),body:A().trim().min(1).max(16384)}),L({}),L({url:A().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status`.split(`.`));let Mf=V([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),Nf=V([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);L({threadId:A(),title:A(),harnessId:A(),state:Mf,reason:Nf,inactiveMs:M().nonnegative()}),L({threadId:G,turnId:gl});let Pf=I({email:A().trim().min(1).max(320).optional(),label:A().trim().min(1).max(256).optional(),plan:A().trim().min(1).max(128).optional(),credits:Nl.optional(),balance:Pl.optional()}).strict();function Ff(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 If=Ff(Pf),Lf={harnessId:W,harnessName:A().trim().min(1).max(128)},Rf=I(Lf).strict();I({}).strict(),I({sources:F(Rf).max(128)}).strict(),I({harnessId:W,refresh:P().optional()}).strict(),I({...Lf,account:If.nullable(),accounts:F(If).max(8).optional()}).strict(),I({refresh:P().optional()}).strict(),I({accounts:F(Ff(Pf.extend(Lf))).max(128)}).strict(),I({harnessId:Ql,model:q.optional(),thinkingOptionId:J.optional(),permissionModeId:vl.optional(),prewarm:H(!0).optional()}).strict();let zf=A().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);I({harnessId:Ql}).strict().extend({path:zf.nullable()}),I({path:zf.nullable(),restartRequired:P()}).strict(),I({harnessId:W,action:V([`check`,`update`,`install`]),confirmedVersion:A().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let Bf=I({currentVersion:A().min(1).max(128),latestVersion:A().min(1).max(128),updateAvailable:P(),canUpdate:P(),latestVerifiedVersion:A().min(1).max(128).optional(),confirmationRequired:H(!0).optional(),versionKind:V([`cli`,`application`]).optional(),manualUpdateUrl:Ys().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:A().max(2048).optional(),messageCode:A().min(1).max(128).optional(),notice:ml.optional(),latestVersionKind:V([`unknown`,`tracking-branch`]).optional()}).strict();I({taskId:A().uuid()}).strict(),z(`status`,[I({taskId:A().uuid(),status:H(`running`)}).strict(),I({taskId:A().uuid(),status:H(`succeeded`),result:Bf}).strict(),I({taskId:A().uuid(),status:H(`failed`),error:I({code:M().int(),message:A().min(1).max(2048)}).strict()}).strict()]);let Vf=A().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Hf=A().trim().min(1),Uf=V([`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`]),Wf=I({accountId:Vf,label:Hf.max(256),email:A().email().max(320).optional(),planType:Uf.optional()}).strict(),Gf=V([`ready`,`unavailable`]);I({version:H(2),currentAccountId:Vf.nullable(),phase:Gf,revision:M().int().nonnegative(),instanceId:Hf.max(1024).optional(),accounts:F(Wf).max(1)}).strict(),I({accountId:Vf,refresh:P().optional()}).strict(),I({accountId:Vf,usage:Dl.nullable(),accountCredits:Nl.optional(),freshness:V([`live`,`cached`]),observedAt:A().datetime().nullable()}).strict();let Kf=1e3,qf=A().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Jf=qf.max(1024),Yf=I({nativeSessionId:Jf,title:qf.max(4096).nullable(),updatedAt:M().int().nonnegative().max(864e13),cwd:qf.max(16384),running:P().nullable()}).strict();I({}).strict(),I({harnesses:F(I({harnessId:Ql,name:qf.max(128)}).strict()).max(128)}).strict(),I({harnessId:Ql,query:A().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:M().int().nonnegative().safe().optional(),limit:M().int().min(1).max(Kf).optional()}).strict(),I({candidates:F(Yf).max(Kf),total:M().int().nonnegative().safe()}).strict(),I({harnessId:Ql,nativeSessionId:Jf}).strict(),I({threadId:qf.max(1024).pipe(G)}).strict();let Xf=A().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Zf=Jf,Qf=Yf;I({}).strict(),I({candidates:F(Qf).max(1e3)}).strict(),I({nativeSessionId:Zf}).strict(),I({threadId:Xf.max(1024).pipe(G)}).strict(),I({threadId:G,lastTurnId:gl}).strict(),I({threadId:G}).strict();let $f=A().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();I({commands:F(I({id:$f,invocation:A().min(1).max(128),label:A().trim().min(1).max(128),description:A().trim().min(1).max(512).optional(),localizations:pl.optional(),argumentMode:V([`none`,`text`]),kind:V([`command`,`skill`]).optional()}).strict()),warnings:F(A().min(1)).optional(),source:V([`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)}),I({harnessId:W,cwd:A().min(1).optional()}).strict(),I({threadId:G}).strict(),I({threadId:G,commandId:$f,turnId:gl.optional(),arguments:ll.optional()}).strict(),I({accepted:H(!0),turnId:gl.optional()}).strict();let ep=H(`2.0`).optional(),Z=yc().optional(),tp=A().min(1),np=R([A(),M().int()]),rp=I({code:M().int(),message:A(),data:U.optional()}).catchall(U).superRefine(il([`data`]));R([I({jsonrpc:ep,id:np,method:tp,params:U.optional(),result:Z,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`params`,`result`,`error`])),I({jsonrpc:ep,id:Z,method:tp,params:U.optional(),result:Z,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`id`,`params`,`result`,`error`])),I({jsonrpc:ep,id:np,method:Z,params:Z,result:U,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`method`,`params`,`error`])),I({jsonrpc:ep,id:np,method:Z,params:Z,result:Z,error:rp}).catchall(U).superRefine(il([`jsonrpc`,`method`,`params`,`result`]))]);let ip=A().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});L({harnessId:W,nativeSessionId:ip,locator:U.optional(),formatVersion:H(1)}).superRefine(il([`locator`])),L({harnessId:W,nativeSessionId:ip,nativeTurnKey:ip,formatVersion:H(1)}),L({harnessId:W,nativeSessionId:ip,checkpointId:ip,locator:U.optional(),formatVersion:H(1)}).superRefine(il([`locator`]));let ap=A().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),op=V([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),sp=L({version:ap,installation:op,phase:V([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:M().int().nonnegative(),downloadedBytes:M().int().nonnegative().optional(),totalBytes:M().int().positive().optional(),error:A().min(1).max(500).nullable(),serviceStopOutput:A().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`})});L({});let cp=A().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`);L({currentVersion:ap,installation:op.nullable(),latestVersion:ap.nullable(),updateAvailable:P(),installationAvailable:P(),releaseNotes:A().min(1).max(2e4).nullable(),releaseNotesUrl:cp.nullable(),status:sp.nullable(),error:A().min(1).max(500).nullable()}),L({status:sp}),L({status:sp.nullable()});let lp=L({icon:A().min(1).max(16).optional(),title:A().min(1).max(120),body:A().min(1).max(1200),contributors:F(A().min(1).max(39)).max(30)}),up=L({summary:A().min(1).max(600).optional(),themes:F(lp).min(1).max(12)}),dp=L({version:ap,publishedAt:rl(),url:A().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:up.nullable(),en:up.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});L({manual:P().optional()}),L({announcement:dp.nullable(),unread:P()}),L({version:ap}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let fp=V([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);I({runningVersion:A().nullable(),installedVersion:A().nullable(),restartRequired:P(),remote:P(),updateSupported:P(),update:I({phase:fp,targetVersion:A().nullable(),error:A().nullable()})});let pp=I({version:A().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();I({hostname:A().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable(),action:V([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:P().optional(),version:A().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),I({state:V([`installed`,`not-installed`])}).strict();let Q=A().min(1).max(1024),mp={hostId:Q.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},$={...mp,threadId:Q},hp=A().min(1).max(8e3),gp={text:hp,requestId:Q};z(`accepted`,[I({accepted:H(!0),startQueuedItemId:Q.optional()}),I({accepted:H(!1),code:V([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:A()})]),z(`available`,[I({available:H(!1)}),I({available:H(!0),items:F(I({id:Q,clientUserMessageId:Q,preview:A().max(801)})).max(100)})]);let _p=z(`kind`,[L({kind:H(`hosts`)}),L({kind:H(`create`),...mp,cwd:A().min(1).max(8192),epoch:Q}),L({kind:H(`projectHarnesses`),...mp,epoch:Q}),L({kind:H(`inspectHarness`),...mp,epoch:Q,cwd:A().min(1).max(8192),harnessId:Q}),L({kind:H(`startSelected`),...mp,epoch:Q,cwd:A().min(1).max(8192),harnessId:Q,model:A().min(1).max(4096),serviceTier:V([`priority`,`ultrafast`]).optional(),reasoningEffort:Q.optional()}),L({kind:H(`status`),...$}),L({kind:H(`list`),...mp,cursor:A().nullable(),archived:P(),includeLoaded:H(!0).optional()}),L({kind:H(`read`),...$,page:L({cursor:A().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:V([`asc`,`desc`]).optional(),limit:M().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),L({kind:H(`usage`),...$,epoch:Q}),L({kind:H(`configure`),...$,epoch:Q,modelId:Q.optional(),serviceTier:Ll.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`}),L({kind:H(`prompt`),...$,epoch:Q,text:hp,requestId:Q.optional()}),L({kind:H(`queue`),...$,epoch:Q}),L({kind:H(`delivery`),...$,epoch:Q,action:z(`kind`,[L({kind:H(`enqueue`),...gp}),L({kind:H(`steer`),...gp,turnId:Q}),L({kind:H(`remove`),itemId:Q}),L({kind:H(`start`),itemId:Q,onlyIfHead:H(!0).optional()}),L({kind:H(`sendNow`),itemId:Q})])}),L({kind:H(`interrupt`),...$,epoch:Q,turnId:Q}),L({kind:H(`rename`),...$,epoch:Q,name:A().min(1).max(512)}),L({kind:H(`archive`),...$,epoch:Q,archived:P()}),L({kind:H(`respond`),...$,epoch:Q,requestId:R([Q,M().int()]),result:B(A(),_c())})]),vp=A().min(1).max(1024),yp=I({hostId:vp,displayName:A().min(1).max(1024),source:V([`codex-managed`,`discovered`]),sshAlias:A().max(1024).nullable(),sshHost:A().min(1).max(1024),sshPort:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable(),autoConnect:P(),connectionAnalyticsId:A().max(1024).optional()}),bp=L({displayName:A().min(1).max(1024),hostname:A().min(1).max(1024),sshPort:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable()});z(`action`,[L({action:H(`session`),operation:_p}),L({action:H(`list`)}),L({action:H(`catalog`)}),L({action:H(`read-thread`),hostId:vp.refine(e=>e!==`local`),input:Id}),L({action:H(`save`),draft:bp,previous:yp.nullable()}),L({action:H(`remove`),previous:yp}),L({action:H(`connect`),hostId:vp,enabled:P()}),L({action:H(`state`),hostId:vp}),L({action:H(`runtime`),hostId:vp}),L({action:H(`update`),hostId:vp.refine(e=>e!==`local`),version:pp.shape.version})]),R([L({result:U}),L({error:L({code:M().int(),message:A()})})]),L({prompt:A().trim().min(1).max(2e3),cwd:A().max(4096).nullable()}),A().trim().min(1).max(60).nullable();let xp=A().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),Sp=R([A(),I({en:A()}).catchall(A())]),Cp=I({title:Sp.optional(),description:Sp.optional(),icon:A().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:A().optional()});I({extensions:F(I({id:xp,name:A().min(1).max(214),version:A().min(1).max(128),format:H(`dsh`),supportedTargets:Dc([H(`web`)]),enabledTargets:F(H(`web`)).max(1),source:A().min(1).max(4096),projectUrl:A().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:A(),meta:Cp.optional(),loadError:A().optional()})),loadedIds:F(xp),safeMode:P(),storeError:A().optional()});let wp=A().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}/`);I({spec:A().trim().min(1).max(4096),registry:wp.optional()}).strict(),I({id:xp,enabled:P()}).strict(),I({id:xp}).strict(),H(1);function Tp(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 xp={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
116
- `,r:`\r`,t:` `},Sp=/[\\\u0000-\u001f]/u;function Cp(e){return e===` `||e===`
117
- `||e===`\r`||e===` `}function wp(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(Sp),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++)wp(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=xp[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&&Sp.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(Cp(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(Cp(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(Cp(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(Cp(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(Cp(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(Cp(e))return;this.fail();return;
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 Ep={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
116
+ `,r:`\r`,t:` `},Dp=/[\\\u0000-\u001f]/u;function Op(e){return e===` `||e===`
117
+ `||e===`\r`||e===` `}function kp(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(Dp),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++)kp(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=Ep[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&&Dp.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(Op(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(Op(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(Op(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(Op(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(Op(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(Op(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:Tp(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){Cp(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===`}`||Cp(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 Tp(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function Ep(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 Dp(e){return Object.getPrototypeOf(e)===null&&Ep(e,`Object`)}function Op(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Ep(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&Dp(n)}function kp(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&Dp(t)}function Ap(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function jp(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(!Op(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(!kp(r))return;let o=Ap(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];
121
+ default:Ap(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){Op(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===`}`||Op(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 Ap(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function jp(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 Mp(e){return Object.getPrototypeOf(e)===null&&jp(e,`Object`)}function Np(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!jp(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&Mp(n)}function Pp(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&Mp(t)}function Fp(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function Ip(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(!Np(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(!Pp(r))return;let o=Fp(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 Mp(e){return jp(e,!0)}function Np(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
123
+ if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function Lp(e){return Ip(e,!0)}function Rp(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 Pp(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 Fp=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]`))}},Ip=class{rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;anyNotifier=new Fp(()=>{});faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){let r=this.rows.get(e);r?.kind===`sequenced`&&n<=r.seq||(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e))}applyLive(e,t,n){let r=this.rows.get(e);r?.kind===`sequenced`&&n<r.seq||(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e))}applyCached(e){for(let t of Object.keys(e))this.rows.get(t)?.kind!==`sequenced`&&(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t))}seed(e,t,n){for(let[e,t]of this.rows)t.kind===`cached`&&(this.rows.delete(e),this.changed(e));let r=e.values;for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new Fp(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},Lp=class{readRemote;values;pending=/* @__PURE__ */ new Map;constructor(e,t){this.readRemote=e,this.values=new Map(t)}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.values.set(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}};function Rp(){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 zp(e){return{kind:`leaf`,entries:e,length:e.length}}function Bp(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Vp(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 Hp(e,t,n,r){let i;return{get entries(){return i??=Vp(e),i},hasMore:t,revision:n,change:r}}var Up=class{listeners=/* @__PURE__ */ new Set;window=zp([]);snapshot=Hp(this.window,!1,0,{kind:`replace`,entries:[]});getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=zp(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Bp(zp(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Bp(this.window,zp(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Vp(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=zp(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Hp(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Wp(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Gp(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Kp(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 qp(e){let t=Mp(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Jp(e){let t=[];for(let n of e){let e=Yp(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 Yp(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`:{Qp(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Zp(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Xp(t,e.length,t.type),t}case`tool-call-chunks`:{Qp(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Zp(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 Xp(t,e.length,t.type),t}case`chunk`:{Qp(t,[`type`,`time`,`chunk`],`chunk`);let e=Gp(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=qp(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Np({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Xp(e,t,n){if(Gp(e.time0),Kp(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 Zp(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Qp(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 $p=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Jp(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=em(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 em(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function tm(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let nm={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},rm={...nm,turnWindow:{...nm.turnWindow,minMessages:200}};var im=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 $p;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Up;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Lp(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Ip,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 Fp(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){let t=Rp(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}activeTurnForSteering(){let e=this.projections.get(ff);return typeof e==`string`?e:null}async prompt(e,t,n,r){let i=r??Rp();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=Wp(),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:Wp()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}return!s.ok&&s.error.code===`remote/outcome-unknown`&&this.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(this.acceptPrompt(),s):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:s.error,requestId:i},this.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i)}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...nm})}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,...rm}),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}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:this.toolOutputs.values,entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(pf),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(nm),e!==this.openGeneration||this.events!==n)return;this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:tm(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=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,pf),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:om(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=om(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,om(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,am(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){let n=this.submissionSettlements.get(e);
127
+ t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function zp(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 Bp=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 Vp(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(!Vp(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)||!Vp(r[e],i[e]))return!1;return!0}var Hp=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new Bp(()=>{});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&&Vp(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&&Vp(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&&Vp(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 Bp(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},Up=class{readRemote;values;pending=/* @__PURE__ */ new Map;constructor(e,t){this.readRemote=e,this.values=new Map(t)}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.values.set(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}};function Wp(){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 Gp(e){return{kind:`leaf`,entries:e,length:e.length}}function Kp(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function qp(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 Jp(e,t,n,r){let i;return{get entries(){return i??=qp(e),i},hasMore:t,revision:n,change:r}}var Yp=class{listeners=/* @__PURE__ */ new Set;window=Gp([]);snapshot=Jp(this.window,!1,0,{kind:`replace`,entries:[]});getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=Gp(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Kp(Gp(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Kp(this.window,Gp(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=qp(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=Gp(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Jp(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Xp(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Zp(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Qp(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 $p(e){let t=Lp(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function em(e){let t=[];for(let n of e){let e=tm(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 tm(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`:{im(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=rm(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return nm(t,e.length,t.type),t}case`tool-call-chunks`:{im(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=rm(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 nm(t,e.length,t.type),t}case`chunk`:{im(t,[`type`,`time`,`chunk`],`chunk`);let e=Zp(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=$p(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Rp({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function nm(e,t,n){if(Zp(e.time0),Qp(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 rm(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function im(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 am=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of em(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=om(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 om(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function sm(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let cm={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},lm={...cm,turnWindow:{...cm.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 am;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Yp;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Up(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Hp,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 Bp(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){let t=Wp(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}activeTurnForSteering(){let e=this.projections.get(kf);return typeof e==`string`?e:null}async prompt(e,t,n,r){let i=r??Wp();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=Xp(),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:Xp()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}return!s.ok&&s.error.code===`remote/outcome-unknown`&&this.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(this.acceptPrompt(),s):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:s.error,requestId:i},this.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i)}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...cm})}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,...lm}),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}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:this.toolOutputs.values,entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(Af),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(cm),e!==this.openGeneration||this.events!==n)return;this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:sm(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=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,Af),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:fm(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=fm(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,fm(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,dm(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){let n=this.submissionSettlements.get(e);
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 am(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function om(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 sm=class{views=/* @__PURE__ */ new Map;take(e){let t=this.views.get(e);return this.views.delete(e),t}remember(e,t){if(this.views.delete(e),this.views.set(e,t),this.views.size<=8)return;let n=this.views.keys().next().value;return this.views.delete(n),n}delete(e){this.views.delete(e)}clear(){this.views.clear()}};function cm(e){return e===-1?-1:p(e)}let lm=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]);var um=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new sm;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;listRequestWorkspaceId;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];notifier=new Fp(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r){let t=this.recentViews.remember(e,r);t&&this.projectionStores.get(t)?.discard(pf)}return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.listMutations=null,this.listInflight=null,this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new im(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 Ip;let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.values();this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.values()===a&&r.clear():r.seed({...t.value,asOfSeq:cm(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){return this.nextCursor?this.refreshList(this.nextCursor,e):Promise.resolve()}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let n=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0,this.listRequestWorkspaceId=e===void 0?void 0:t;let r=this.summaries,a=[];return this.listMutations=a,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==a)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...r.filter(e=>!o.has(e.sessionId)&&(s||!n&&t.has(e.sessionId)))],l=this.listPhase===`pending`?c:bp(r,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of a)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=a.reduce(dm,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===a&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==a)return;this.listState=`error`,this.listError=e}finally{this.listMutations===a&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=fm(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:fm(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq)),n}mergeSummary(e){this.recordMutation({kind:`upsert`,summary:e}),this.updateParentAvailability()}recordMutation(e){this.disposed||(this.listMutations?.push(e),this.summaries=dm(this.summaries,e),this.notifier.markDirty())}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):(this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq)),this.notifier.markDirty())}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=cm(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,pf)}this.notifier.markDirty()}handleSessionAdded(e,t=!0){t&&this.summaryOnlyIds.delete(e.sessionId),this.mergeSummary(e),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let n=this.sessions.get(e.sessionId);n?.handleRestored(),n?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=cm(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:Tp(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){this.summaryOnlyIds.delete(e);let t=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`);this.recordMutation(t?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e}),t?this.sessions.get(e)?.handleRunning(!1):(this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved());let n=this.projectionStores.get(e)?.values().subagentCatalog;!t&&(n===void 0||n.length===0)&&this.projectionStores.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e),this.projectionLoads.delete(e);for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e),this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0}),this.updateParentAvailability(),this.sessions.get(e)?.handleRunning(t)}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t})}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(lm);this.listMutations=null,this.listInflight=null,this.nextCursor=void 0,this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=Pp(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);return e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e),{items:this.itemsCache,hasMore:!!this.nextCursor,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,errorWorkspaceId:this.listError&&this.listRequestIsMore?this.listRequestWorkspaceId??null:null,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([e,t])=>[e,{values:t.values(),state:`idle`,error:null,...this.projectionLoads.get(e)}]))}}};function dm(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.find(e=>e.sessionId===t.summary.sessionId);if(n===void 0)return[t.summary,...e];let r={...n,blank:n.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...n.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...n.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...n.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};return r.cwd===n.cwd&&r.parentSessionId===n.parentSessionId&&r.origin===n.origin&&r.blank===n.blank&&r.agentAvailable===n.agentAvailable&&r.running===n.running?[...e]:e.map(e=>e.sessionId===t.summary.sessionId?r:e)}case`remove`:return e.filter(e=>e.sessionId!==t.sessionId);case`status`:return e.map(e=>e.sessionId===t.sessionId&&(e.running!==t.running||e.agentAvailable!==t.agentAvailable||t.running&&e.blank)?{...e,running:t.running,agentAvailable:t.agentAvailable,blank:e.blank&&!t.running}:e);case`activity`:return e.map(e=>e.sessionId===t.sessionId&&t.updatedAt>e.updatedAt?{...e,updatedAt:t.updatedAt}:e);case`engaged`:return e.map(e=>e.sessionId===t.sessionId&&e.blank?{...e,blank:!1}:e)}}function fm(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var pm=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},mm=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 hm(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 gm(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 _m(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let vm=Object.freeze({referenceCount:0,retainedBy:_m({})});async function ym(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 bm=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]);ym(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()}},xm=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new um(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}loadSummary(e){return this.manager.loadSummary(e)}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new pm(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 mm(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,gm(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:_m({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new bm(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?vm:Object.freeze({referenceCount:r,retainedBy:_m(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??vm}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:vm,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,errorWorkspaceId:c,headRefreshRevision:l,summaryOnlyIds:u}=this.manager.getListSnapshot(),d=[],f={};for(let e of t)d.push(e.sessionId),f[e.sessionId]={id:e.sessionId,displayTitle:hm(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:this.retentionSnapshot(e.sessionId).retainedBy,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=f[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?f[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(f[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(f[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;f[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:d,byId:f,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,listErrorWorkspaceId:c,headRefreshRevision:l??0,summaryOnlyIds:u??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let Sm=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function Cm(e){let t=e.remote,n=e.get(`connection`),r=new xm(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=Up,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=pm,n.SessionEventStream=pe,n.SessionForkError=mm,n.apply=Cm,n.createScope=_e,n.createSessionControlStream=fe,n.inject=Sm,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 dm(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function fm(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 pm=class{views=/* @__PURE__ */ new Map;take(e){let t=this.views.get(e);return this.views.delete(e),t}remember(e,t){if(this.views.delete(e),this.views.set(e,t),this.views.size<=8)return;let n=this.views.keys().next().value;return this.views.delete(n),n}delete(e){this.views.delete(e)}clear(){this.views.clear()}};function mm(e){return e===-1?-1:p(e)}let hm=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]),gm=/* @__PURE__ */ new Set([...Af,`codexhostTurnTimes`,`codexhostUsage`,`contextPressure`,`contextBreakdown`,`inbox`,`queueState`,`turnOutline`,`sessionStats`,`compacting`]);var _m=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new pm;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;listRequestWorkspaceId;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];projectionSnapshotCache=/* @__PURE__ */ new Map;projectionsBySessionCache={};notifier=new Bp(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r){let t=this.recentViews.remember(e,r);t&&this.projectionStores.get(t)?.discard(Af)}return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.listMutations=null,this.listInflight=null,this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new 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 Hp(gm);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:mm(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){return this.nextCursor?this.refreshList(this.nextCursor,e):Promise.resolve()}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let n=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0,this.listRequestWorkspaceId=e===void 0?void 0:t;let r=this.summaries,a=[];return this.listMutations=a,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==a)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...r.filter(e=>!o.has(e.sessionId)&&(s||!n&&t.has(e.sessionId)))],l=this.listPhase===`pending`?c:Tp(r,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of a)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=a.reduce(vm,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===a&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==a)return;this.listState=`error`,this.listError=e}finally{this.listMutations===a&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=ym(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:ym(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=vm(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))&&!gm.has(e.key)&&this.notifier.markFrameDirty()}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=mm(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,Af)}this.notifier.markFrameDirty()}handleSessionAdded(e,t=!0){let n=t&&this.summaryOnlyIds.delete(e.sessionId),r=this.mergeSummary(e);n&&!r&&this.notifier.markFrameDirty(),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let i=this.sessions.get(e.sessionId);i?.handleRestored(),i?.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=mm(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:Ap(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){let t=this.summaryOnlyIds.delete(e),n=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`),r=this.recordMutation(n?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e},`frame`),i=!1;if(n){let t=this.sessions.get(e);i=t?.getSnapshot().running===!0,t?.handleRunning(!1)}else this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved();let a=this.projectionStores.get(e)?.values().subagentCatalog,o=!n&&(a===void 0||a.length===0)&&this.projectionStores.delete(e);this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e);let s=this.projectionLoads.delete(e);!r&&(t||o||s||i)&&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(hm);this.listMutations=null,this.listInflight=null,this.nextCursor=void 0,this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=zp(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,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,errorWorkspaceId:this.listError&&this.listRequestIsMore?this.listRequestWorkspaceId??null:null,projectionsBySession:this.projectionsBySessionCache}}};function vm(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 ym(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var bm=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},xm=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 Sm(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 Cm(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 wm(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let Tm=Object.freeze({referenceCount:0,retainedBy:wm({})});async function Em(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 Dm=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]);Em(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()}},Om=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 _m(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}loadSummary(e){return this.manager.loadSummary(e)}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new bm(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 xm(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,Cm(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:wm({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new Dm(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?Tm:Object.freeze({referenceCount:r,retainedBy:wm(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??Tm}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:Tm,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,errorWorkspaceId:c,headRefreshRevision:l,summaryOnlyIds:u}=this.manager.getListSnapshot(),d=[],f={};for(let e of t){d.push(e.sessionId);let t=this.retentionSnapshot(e.sessionId).retainedBy,n=this.projectedItemCache.get(e.sessionId);if(n!==void 0&&n.entry===e&&n.retainedBy===t){f[e.sessionId]=n.summary;continue}let r={id:e.sessionId,displayTitle:Sm(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}),f[e.sessionId]=r}if(this.projectedItemCache.size>t.length)for(let e of this.projectedItemCache.keys())f[e]===void 0&&this.projectedItemCache.delete(e);for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=f[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?f[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(f[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(f[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;f[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:d,byId:f,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,listErrorWorkspaceId:c,headRefreshRevision:l??0,summaryOnlyIds:u??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let km=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function Am(e){let t=e.remote,n=e.get(`connection`),r=new Om(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=Yp,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=bm,n.SessionEventStream=pe,n.SessionForkError=xm,n.apply=Am,n.createScope=_e,n.createSessionControlStream=fe,n.inject=km,n.scopeOf=ve,t.exports}});