@codexhost/cli-darwin-x64 0.23.0 → 0.24.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 (56) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +1565 -1805
  4. package/app/console-web.js +5786 -1600
  5. package/app/desktop-controller.mjs +13104 -2842
  6. package/app/host-runtime.mjs +50518 -51753
  7. package/app/plugins/antigravity/plugin.mjs +1932 -1148
  8. package/app/plugins/claude-code/plugin.mjs +1676 -1218
  9. package/app/plugins/codebuddy/plugin.mjs +1266 -850
  10. package/app/plugins/codex-usage/plugin.mjs +916 -737
  11. package/app/plugins/copilot/plugin.mjs +838 -640
  12. package/app/plugins/cursor-cli/plugin.mjs +1058 -747
  13. package/app/plugins/deepseek-harness/plugin.mjs +1302 -1070
  14. package/app/plugins/devin/plugin.mjs +949 -752
  15. package/app/plugins/grok/plugin.mjs +1132 -964
  16. package/app/plugins/hermes/plugin.mjs +1084 -905
  17. package/app/plugins/kimi-code/plugin.mjs +977 -804
  18. package/app/plugins/kiro-cli/plugin.mjs +951 -758
  19. package/app/plugins/omp/plugin.mjs +1408 -1169
  20. package/app/plugins/opencode/plugin.mjs +1385 -1142
  21. package/app/plugins/pi/plugin.mjs +1515 -1287
  22. package/app/plugins/qoder/plugin.mjs +861 -676
  23. package/app/plugins/qoder-cn/plugin.mjs +861 -676
  24. package/app/plugins/qwen-code/plugin.mjs +1060 -888
  25. package/app/plugins/workbuddy/plugin.mjs +1272 -856
  26. package/app/plugins/zcode/plugin.mjs +1529 -880
  27. package/app/renderer-extension.js +11568 -7827
  28. package/app/web/assets/index-CTCFIQbU.css +1 -0
  29. package/app/web/assets/index-IvFk9KT-.js +203 -0
  30. package/app/web/codexhost-settings.js +4472 -36194
  31. package/app/web/index.html +2 -2
  32. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  33. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  34. package/app/web/plugins/deepseek-ai__dsh-client-ui-approval/client.js +1 -1
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +74 -74
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +75 -64
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +19 -16
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-input-trigger/client.js +1 -1
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-layout/client.js +2 -2
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +2 -2
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
  42. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar/client.js +2 -2
  43. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.js +9 -9
  44. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +1 -1
  45. package/app/web/plugins/deepseek-ai__dsh-client-ui-theme/client.js +1 -1
  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 +3 -3
  48. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +7 -7
  49. package/app/web/sw.js +8 -1
  50. package/app/web-modules/server.mjs +2682 -5540
  51. package/bin/codexhost +0 -0
  52. package/libexec/codexhost-shim +0 -0
  53. package/libexec/codexhost-updater +0 -0
  54. package/package.json +1 -1
  55. package/app/web/assets/index-DJW4bmyx.css +0 -1
  56. package/app/web/assets/index-Dyh1KzAB.js +0 -201
@@ -1,6 +1,6 @@
1
- window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,factory:e=>{var t={exports:{}},n=t.exports;Object.defineProperty(n,Symbol.toStringTag,{value:`Module`});let r=e("@deepseek-ai/cordis"),i=e("@deepseek-ai/dsh-api-gateway/client"),a=e("@deepseek-ai/dsh-client-store");var o=class extends Error{code;details;isDSHRemoteError=!0;constructor(e,t,n,r){super(t,r),this.code=e,this.details=n,this.name=`RemoteError`}};let s=Symbol.for(`dsh.typert.owned-value`);function c(e,t){let n=!0;return{[s]:!0,value:e,[Symbol.dispose](){n&&(n=!1,t())}}}function l(e){return e}function u(e){return e.event.seq}function d(e){return e.event.seq}function f(e){return e}function p(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionSeq must be a non-negative safe integer, got ${String(e)}`);return f(e)}function ee(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(e)}`);return f(e)}let te=/* @__PURE__ */ new Set(/* @__PURE__ */ `agent-preset/selected.agent/inbox/spliced.approval/asked.approval/decided.approval/policy.assistant/attempt.assistant/message.command/done.command/run.compaction/end.compaction/prune.compaction/start.compaction/summary.deliverables/presented.developer/message.feedback/message-delete.feedback/message-put.feedback/record.goal/change.hook/invoked.hook/result.image/offload.llm/retry.llm/retry-started.model/selection.permission/preset.plan/mode.request/context.request/header.sandbox/mode.schedule/change.session-log-deepseek/delivery-accepted.session/end-seed.session/title.session/title-llm-request.step/end.step/start.subagent/catalog.subagent/descriptor.subagent/model-selection-policy.system/message.team/member.team/message/delivered.team/message/queued.team/task.todo/write.tool-workflow/agent-end.tool-workflow/agent-start.tool-workflow/run-end.tool-workflow/run-start.tool/call.tool/ptc-dispatch.tool/ptc-dispatch-start.tool/result.turn/end.turn/start.user/message.web/deepseek-search-llm-request.workspace/changes`.split(`.`)),ne=/* @__PURE__ */ new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function re(e){return ne.has(e)}function m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ie(e,t){let n=e.data;if(ne.has(e.type)&&m(n)){let r=e.type===`user/message`?n:n.message;if(m(r)){if(e.type===`developer/message`!=(r.role===`developer`))throw Error(`${t} developer/message and developer role must occur together`);if(r.role!==`developer`&&Array.isArray(r.content)&&r.content.some(e=>m(e)&&(e.type===`tool-addition`||e.type===`tool-removal`)))throw Error(`${t} tool-change blocks require developer role`);if(e.type===`developer/message`&&Array.isArray(r.content)){let e=!1;for(let n of r.content)if(!(!m(n)||n.type!==`tool-addition`&&n.type!==`tool-removal`)){if(typeof n.toolName!=`string`||n.toolName.length===0)throw Error(`${t} ${n.type} requires a nonempty toolName`);if(n.type===`tool-addition`&&(e=!0,Object.hasOwn(n,`tool`)))throw Error(`${t} tool-addition must omit inline tool definitions`)}if(e?!ae(n.headerSeq):Object.hasOwn(n,`headerSeq`))throw Error(`${t} requires headerSeq exactly when tool additions are present`)}}}if(e.type===`request/header`){if(!m(n))throw Error(`${t} data must be an object`);let e=n.header;if(!m(e))throw Error(`${t} header must be an object`);if(Object.hasOwn(e,`system`))throw Error(`${t} must omit header.system; use system/message`);if(Array.isArray(e.tools)&&e.tools.length===0)throw Error(`${t} must omit empty tools`);let r=e.adapterDefaults;if(m(r)&&Object.keys(r).length===0)throw Error(`${t} must omit empty adapterDefaults`)}else if(e.type===`tool/result`){if(!m(n))throw Error(`${t} data must be an object`);if(n.error===void 0)return;let e=n.message;if(!m(e)||e.isError!==!0)throw Error(`${t} error requires message.isError === true`)}}function ae(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}function oe(e){let t=e;return Object.keys(t).length===3&&Object.hasOwn(t,`op`)&&Object.hasOwn(t,`startSeq`)&&Object.hasOwn(t,`endSeq`)&&t.op===`replace`&&ae(t.startSeq)&&ae(t.endSeq)}function se(e){let t=e;if(!re(e.type)){if(!te.has(e.type)&&e.ignorable===!0)return;if(t.surfaceOp!==void 0)throw Error(`session event "${e.type}" is not surface-eligible and cannot carry surfaceOp`);if(t.sourceEventSeqs!==void 0)throw Error(`session event "${e.type}" is not surface-eligible and cannot carry sourceEventSeqs`);return}let n=t.surfaceOp;if(n===void 0)throw Error(`session event "${e.type}" is surface-eligible and requires a surfaceOp marker`);if(n===`append`)return n;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`session event "${e.type}" carries an invalid surfaceOp`);if(!oe(n))throw Error(`session event "${e.type}" carries an invalid replace surfaceOp`);return n}function ce(e,t){let n=e.sourceEventSeqs;if(e.type===`assistant/message`&&n!==void 0)throw Error(`assistant/message embeds its source stream and cannot carry sourceEventSeqs`);let r=/* @__PURE__ */ new Set;if(n!==void 0){if(!Array.isArray(n))throw Error(`sourceEventSeqs on event at seq ${e.seq} must be an array when present`);if(n.length===0)throw Error(`sourceEventSeqs must not be empty`);let t;for(let i of n){if(!ae(i))throw Error(`session event "${e.type}" sourceEventSeqs must densely contain non-negative safe integers`);r.add(i),t===void 0&&i>=e.seq&&(t=i)}if(r.size!==n.length)throw Error(`sourceEventSeqs must not contain duplicates`);if(t!==void 0)throw Error(`sourceEventSeqs must reference earlier events: ${t} >= current seq ${e.seq}`)}let i=t.filter(e=>!r.has(e));if(i.length>0)throw Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${i.join(`, `)}`)}function le(e){let t=se(e);if(t!==void 0&&t!==`append`&&(t.startSeq>=e.seq||t.endSeq>=e.seq))throw Error(`surface replace at seq ${e.seq}: startSeq and endSeq must reference earlier events`);return t!==void 0&&ce(e,[]),t}function ue(e){let t=`session wire event`;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);let n=e;for(let e of Object.keys(n))switch(e){case`type`:case`seq`:case`time`:case`data`:case`ignorable`:case`surfaceOp`:case`sourceEventSeqs`:break;default:throw Error(`${t} has unexpected field ${e}`)}let r=n.seq;if(typeof n.type!=`string`||typeof r!=`number`||!Number.isSafeInteger(r)||r<0||Object.is(r,-0)||typeof n.time!=`number`||!Number.isSafeInteger(n.time)||!Object.hasOwn(n,`data`)||n.data===void 0||Object.hasOwn(n,`ignorable`)&&n.ignorable!==!0)throw Error(`${t} has an invalid envelope`);let i=n;le(i),ie(i,t)}function de(e){switch(e.type){case`replace`:case`prepend`:return{...e,entries:l(e.entries)};case`append`:return{type:`append`,entry:e.entry};case`notification`:return e.notification}}function fe(e,t){let n=e.$stream({name:`session control stream`,open:t=>e.session.control(t),ended:e=>e?new i.RemoteStreamCarrierError(`session control stream ended without a terminal result`):/* @__PURE__ */ Error(`session control stream ended before its opening snapshot`),...t.carrierFailed===void 0?{}:{carrierFailed:t.carrierFailed}});return new i.RemoteSnapshotStream(n,{name:`session control stream`,isSnapshot:e=>e.type===`baseline`,replace:t.accept,update:t.accept,failed:t.failed})}var pe=class extends i.RemoteJournalStream{remote;address;journal;epoch;capture(){return this.journal&&{...this.journal,records:[...this.journal.records]}}get journalEpoch(){return this.epoch}constructor(e,t,n,r){super(e,{name:`session event stream`,emptyCursor:-1,entries:e=>e.records,hasMore:e=>e.hasMore,first:u,last:d,compare:(e,t)=>e-t,follows:(e,t)=>t===e+1,publish:e=>{this.epoch===void 0?this.journal=void 0:e.type===`replace`?this.journal={epoch:this.epoch,cursor:e.entries.at(-1)?.event.seq??-1,records:[...e.entries],hasMore:e.hasMore}:this.journal!==void 0&&e.type===`append`?(this.journal.cursor=e.entry.event.seq,this.journal.records.push(e.entry)):this.journal!==void 0&&e.type===`prepend`&&(this.journal.records.unshift(...e.entries),this.journal.hasMore=e.hasMore),n.publish(de(e))},...n.carrierFailed===void 0?{}:{carrierFailed:n.carrierFailed},failed:n.failed}),this.remote=e,this.address=t,this.journal=r&&{...r,records:[...r.records]},this.epoch=r?.epoch}async*follow(e,t){let n,r=this.journal;for await(let a of this.remote.session.follow({address:this.address,assistantStream:!0,...this.repairRequest(e),...r===void 0?{}:{resume:{epoch:r.epoch,cursor:r.cursor}}},t))if(a.type===`snapshot`){for(let e of a.records)ue(e.event);if(a.assistantStream===void 0)throw new o(`gateway/internal`,`session assistant stream omitted its opted-in opening baseline`,{});let e=a.records,t=a.hasMore;if(a.resumedAfter!==void 0){if(r===void 0||a.epoch!==r.epoch||a.resumedAfter!==r.cursor||a.cursor!==(e.at(-1)?.event.seq??r.cursor)||e.length>0&&e[0]?.event.seq!==r.cursor+1)throw new o(`gateway/internal`,`Invalid session resume baseline`,{});e=[...r.records,...e],t=r.hasMore}let i=a.epoch!==void 0&&a.epoch!==this.epoch;this.epoch=a.epoch,n=a.assistantStream.revision,yield{type:`opened`,...i?{reset:!0}:{},cursor:a.cursor,page:{records:e,hasMore:t,projections:a.projections,assistantStream:a.assistantStream}}}else if(a.type===`assistant-stream`){let e=(n??0)+1;if(a.frame.revision!==e)throw new i.RemoteStreamCarrierError(`session assistant stream skipped revision ${String(e)}`);n=a.frame.revision,yield{type:`notification`,notification:a}}else a.type===`projection`?yield{type:`notification`,notification:a}:(ue(a.event),yield{type:`entry`,entry:a})}async readPage(e,t,n){let r=await this.remote.session.page({address:this.address,throughSeq:t,...e},n);if(!r.ok)throw r.error;for(let e of r.value.records)ue(e.event);return r.value}repairRequest(e){return{...e.maxMessages===void 0?{}:{maxMessages:e.maxMessages},...e.turnWindow===void 0?{}:{turnWindow:e.turnWindow}}}};function me(e){let t=e.replace(/[/\\]+$/,``),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return t.slice(n+1)}let he=Symbol(`dsh.client.scope`);function ge(){}function _e(e,t){let n=e.plugin(ge),i={sessionId:t};return{fiber:n,ctx:n.ctx.extend({[he]:i,[r.Context.filter](e){let t=ye(e);return t===void 0||t===i}})}}function ve(e){return ye(e)?.sessionId}function ye(e){return e[he]}var be;let xe=/*@__PURE__*/ Object.freeze({status:`aborted`});function h(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:/* @__PURE__ */ new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Se=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Ce=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(be=globalThis).__zod_globalConfig??(be.__zod_globalConfig={});let we=globalThis.__zod_globalConfig;function g(e){return e&&Object.assign(we,e),we}function Te(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Ee(e,t){return typeof t==`bigint`?t.toString():t}function De(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Oe(e){return e==null}function ke(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ae(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}let je=/* @__PURE__*/ Symbol(`evaluating`);function _(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==je)return r===void 0&&(r=je,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Me(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ne(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Pe(e){return JSON.stringify(e)}function Fe(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}let Ie=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Le(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let Re=/* @__PURE__*/ De(()=>{if(we.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function ze(e){if(Le(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Le(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Be(e){return ze(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let Ve=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function He(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ue(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function v(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function We(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}let Ge={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ke(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Ue(e,Ne(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Me(this,`shape`,e),e},checks:[]}))}function qe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Ue(e,Ne(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Me(this,`shape`,r),r},checks:[]}))}function Je(e,t){if(!ze(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ue(e,Ne(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Me(this,`shape`,n),n}}))}function Ye(e,t){if(!ze(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ue(e,Ne(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Me(this,`shape`,n),n}}))}function Xe(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Ue(e,Ne(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Me(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Ze(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Ue(t,Ne(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Me(this,`shape`,i),i},checks:[]}))}function Qe(e,t,n){return Ue(t,Ne(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Me(this,`shape`,i),i}}))}function $e(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function et(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function y(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function tt(e){return typeof e==`string`?e:e?.message}function b(e,t,n){let r=e.message?e.message:tt(e.inst?._zod.def?.error?.(e))??tt(t?.error?.(e))??tt(n.customError?.(e))??tt(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function nt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function rt(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}let it=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Ee,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},at=h(`$ZodError`,it),ot=h(`$ZodError`,it,{Parent:Error});function st(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function ct(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}let lt=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Se;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>b(e,a,g())));throw Ie(t,i?.callee),t}return o.value},ut=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>b(e,a,g())));throw Ie(t,i?.callee),t}return o.value},dt=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Se;return a.issues.length?{success:!1,error:new(e??at)(a.issues.map(e=>b(e,i,g())))}:{success:!0,data:a.value}},ft=/* @__PURE__*/ dt(ot),pt=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>b(e,i,g())))}:{success:!0,data:a.value}},mt=/* @__PURE__*/ pt(ot),ht=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return lt(e)(t,n,i)},gt=e=>(t,n,r)=>lt(e)(t,n,r),_t=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ut(e)(t,n,i)},vt=e=>async(t,n,r)=>ut(e)(t,n,r),yt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return dt(e)(t,n,i)},bt=e=>(t,n,r)=>dt(e)(t,n,r),xt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return pt(e)(t,n,i)},St=e=>async(t,n,r)=>pt(e)(t,n,r),Ct=/^[cC][0-9a-z]{6,}$/,wt=/^[0-9a-z]+$/,Tt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Et=/^[0-9a-vA-V]{20}$/,Dt=/^[A-Za-z0-9]{27}$/,Ot=/^[a-zA-Z0-9_-]{21}$/,kt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,At=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,jt=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Mt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Nt(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}let Pt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ft=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,It=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Lt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Rt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,zt=/^[A-Za-z0-9_-]*$/,Bt=/^https?$/,Vt=/^\+[1-9]\d{6,14}$/,Ht=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Ut=/*@__PURE__*/ RegExp(`^${Ht}$`);function Wt(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Gt(e){return RegExp(`^${Wt(e)}$`)}function Kt(e){let t=Wt({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Ht}T(?:${r})$`)}let qt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Jt=/^-?\d+$/,Yt=/^-?\d+(?:\.\d+)?$/,Xt=/^(?:true|false)$/i,Zt=/^null$/i,Qt=/^[^A-Z]*$/,$t=/^[^a-z]*$/,x=/*@__PURE__*/ h(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),en={number:`number`,bigint:`bigint`,object:`date`},tn=/*@__PURE__*/ h(`$ZodCheckLessThan`,(e,t)=>{x.init(e,t);let n=en[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),nn=/*@__PURE__*/ h(`$ZodCheckGreaterThan`,(e,t)=>{x.init(e,t);let n=en[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rn=/*@__PURE__*/ h(`$ZodCheckMultipleOf`,(e,t)=>{x.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Ae(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),an=/*@__PURE__*/ h(`$ZodCheckNumberFormat`,(e,t)=>{x.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ge[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Jt)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),on=/*@__PURE__*/ h(`$ZodCheckMaxLength`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=nt(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),sn=/*@__PURE__*/ h(`$ZodCheckMinLength`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=nt(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),cn=/*@__PURE__*/ h(`$ZodCheckLengthEquals`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=nt(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ln=/*@__PURE__*/ h(`$ZodCheckStringFormat`,(e,t)=>{var n,r;x.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=/* @__PURE__ */ new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),un=/*@__PURE__*/ h(`$ZodCheckRegex`,(e,t)=>{ln.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),dn=/*@__PURE__*/ h(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Qt,ln.init(e,t)}),fn=/*@__PURE__*/ h(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=$t,ln.init(e,t)}),pn=/*@__PURE__*/ h(`$ZodCheckIncludes`,(e,t)=>{x.init(e,t);let n=He(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),mn=/*@__PURE__*/ h(`$ZodCheckStartsWith`,(e,t)=>{x.init(e,t);let n=RegExp(`^${He(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),hn=/*@__PURE__*/ h(`$ZodCheckEndsWith`,(e,t)=>{x.init(e,t);let n=RegExp(`.*${He(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),gn=/*@__PURE__*/ h(`$ZodCheckOverwrite`,(e,t)=>{x.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var _n=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
1
+ window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,factory:e=>{var t={exports:{}},n=t.exports;Object.defineProperty(n,Symbol.toStringTag,{value:`Module`});let r=e("@deepseek-ai/cordis"),i=e("@deepseek-ai/dsh-api-gateway/client"),a=e("@deepseek-ai/dsh-client-store");var o=class extends Error{code;details;isDSHRemoteError=!0;constructor(e,t,n,r){super(t,r),this.code=e,this.details=n,this.name=`RemoteError`}};let s=Symbol.for(`dsh.typert.owned-value`);function c(e,t){let n=!0;return{[s]:!0,value:e,[Symbol.dispose](){n&&(n=!1,t())}}}function l(e){return e}function u(e){return e.event.seq}function d(e){return e.event.seq}function f(e){return e}function p(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionSeq must be a non-negative safe integer, got ${String(e)}`);return f(e)}function ee(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionLogOffset must be a non-negative safe integer, got ${String(e)}`);return f(e)}let te=/* @__PURE__ */ new Set(/* @__PURE__ */ `agent-preset/selected.agent/inbox/spliced.approval/asked.approval/decided.approval/policy.assistant/attempt.assistant/message.command/done.command/run.compaction/end.compaction/prune.compaction/start.compaction/summary.deliverables/presented.developer/message.feedback/message-delete.feedback/message-put.feedback/record.goal/change.hook/invoked.hook/result.image/offload.llm/retry.llm/retry-started.model/selection.permission/preset.plan/mode.request/context.request/header.sandbox/mode.schedule/change.session-log-deepseek/delivery-accepted.session/end-seed.session/title.session/title-llm-request.step/end.step/start.subagent/catalog.subagent/descriptor.subagent/model-selection-policy.system/message.team/member.team/message/delivered.team/message/queued.team/task.todo/write.tool-workflow/agent-end.tool-workflow/agent-start.tool-workflow/run-end.tool-workflow/run-start.tool/call.tool/ptc-dispatch.tool/ptc-dispatch-start.tool/result.turn/end.turn/start.user/message.web/deepseek-search-llm-request.workspace/changes`.split(`.`)),ne=/* @__PURE__ */ new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function re(e){return ne.has(e)}function m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ie(e,t){let n=e.data;if(ne.has(e.type)&&m(n)){let r=e.type===`user/message`?n:n.message;if(m(r)){if(e.type===`developer/message`!=(r.role===`developer`))throw Error(`${t} developer/message and developer role must occur together`);if(r.role!==`developer`&&Array.isArray(r.content)&&r.content.some(e=>m(e)&&(e.type===`tool-addition`||e.type===`tool-removal`)))throw Error(`${t} tool-change blocks require developer role`);if(e.type===`developer/message`&&Array.isArray(r.content)){let e=!1;for(let n of r.content)if(!(!m(n)||n.type!==`tool-addition`&&n.type!==`tool-removal`)){if(typeof n.toolName!=`string`||n.toolName.length===0)throw Error(`${t} ${n.type} requires a nonempty toolName`);if(n.type===`tool-addition`&&(e=!0,Object.hasOwn(n,`tool`)))throw Error(`${t} tool-addition must omit inline tool definitions`)}if(e?!ae(n.headerSeq):Object.hasOwn(n,`headerSeq`))throw Error(`${t} requires headerSeq exactly when tool additions are present`)}}}if(e.type===`request/header`){if(!m(n))throw Error(`${t} data must be an object`);let e=n.header;if(!m(e))throw Error(`${t} header must be an object`);if(Object.hasOwn(e,`system`))throw Error(`${t} must omit header.system; use system/message`);if(Array.isArray(e.tools)&&e.tools.length===0)throw Error(`${t} must omit empty tools`);let r=e.adapterDefaults;if(m(r)&&Object.keys(r).length===0)throw Error(`${t} must omit empty adapterDefaults`)}else if(e.type===`tool/result`){if(!m(n))throw Error(`${t} data must be an object`);if(n.error===void 0)return;let e=n.message;if(!m(e)||e.isError!==!0)throw Error(`${t} error requires message.isError === true`)}}function ae(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0&&!Object.is(e,-0)}function oe(e){let t=e;return Object.keys(t).length===3&&Object.hasOwn(t,`op`)&&Object.hasOwn(t,`startSeq`)&&Object.hasOwn(t,`endSeq`)&&t.op===`replace`&&ae(t.startSeq)&&ae(t.endSeq)}function se(e){let t=e;if(!re(e.type)){if(!te.has(e.type)&&e.ignorable===!0)return;if(t.surfaceOp!==void 0)throw Error(`session event "${e.type}" is not surface-eligible and cannot carry surfaceOp`);if(t.sourceEventSeqs!==void 0)throw Error(`session event "${e.type}" is not surface-eligible and cannot carry sourceEventSeqs`);return}let n=t.surfaceOp;if(n===void 0)throw Error(`session event "${e.type}" is surface-eligible and requires a surfaceOp marker`);if(n===`append`)return n;if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`session event "${e.type}" carries an invalid surfaceOp`);if(!oe(n))throw Error(`session event "${e.type}" carries an invalid replace surfaceOp`);return n}function ce(e,t){let n=e.sourceEventSeqs;if(e.type===`assistant/message`&&n!==void 0)throw Error(`assistant/message embeds its source stream and cannot carry sourceEventSeqs`);let r=/* @__PURE__ */ new Set;if(n!==void 0){if(!Array.isArray(n))throw Error(`sourceEventSeqs on event at seq ${e.seq} must be an array when present`);if(n.length===0)throw Error(`sourceEventSeqs must not be empty`);let t;for(let i of n){if(!ae(i))throw Error(`session event "${e.type}" sourceEventSeqs must densely contain non-negative safe integers`);r.add(i),t===void 0&&i>=e.seq&&(t=i)}if(r.size!==n.length)throw Error(`sourceEventSeqs must not contain duplicates`);if(t!==void 0)throw Error(`sourceEventSeqs must reference earlier events: ${t} >= current seq ${e.seq}`)}let i=t.filter(e=>!r.has(e));if(i.length>0)throw Error(`surface replace: sourceEventSeqs must include every shadowed surface node; missing ${i.join(`, `)}`)}function le(e){let t=se(e);if(t!==void 0&&t!==`append`&&(t.startSeq>=e.seq||t.endSeq>=e.seq))throw Error(`surface replace at seq ${e.seq}: startSeq and endSeq must reference earlier events`);return t!==void 0&&ce(e,[]),t}function ue(e){let t=`session wire event`;if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`${t} must be an object`);let n=e;for(let e of Object.keys(n))switch(e){case`type`:case`seq`:case`time`:case`data`:case`ignorable`:case`surfaceOp`:case`sourceEventSeqs`:break;default:throw Error(`${t} has unexpected field ${e}`)}let r=n.seq;if(typeof n.type!=`string`||typeof r!=`number`||!Number.isSafeInteger(r)||r<0||Object.is(r,-0)||typeof n.time!=`number`||!Number.isSafeInteger(n.time)||!Object.hasOwn(n,`data`)||n.data===void 0||Object.hasOwn(n,`ignorable`)&&n.ignorable!==!0)throw Error(`${t} has an invalid envelope`);let i=n;le(i),ie(i,t)}function de(e){switch(e.type){case`replace`:case`prepend`:return{...e,entries:l(e.entries)};case`append`:return{type:`append`,entry:e.entry};case`notification`:return e.notification}}function fe(e,t){let n=e.$stream({name:`session control stream`,open:t=>e.session.control(t),ended:e=>e?new i.RemoteStreamCarrierError(`session control stream ended without a terminal result`):/* @__PURE__ */ Error(`session control stream ended before its opening snapshot`),...t.carrierFailed===void 0?{}:{carrierFailed:t.carrierFailed}});return new i.RemoteSnapshotStream(n,{name:`session control stream`,isSnapshot:e=>e.type===`baseline`,replace:t.accept,update:t.accept,failed:t.failed})}var pe=class extends i.RemoteJournalStream{remote;address;journal;epoch;capture(){return this.journal&&{...this.journal,records:[...this.journal.records]}}get journalEpoch(){return this.epoch}constructor(e,t,n,r){super(e,{name:`session event stream`,emptyCursor:-1,entries:e=>e.records,hasMore:e=>e.hasMore,first:u,last:d,compare:(e,t)=>e-t,follows:(e,t)=>t===e+1,publish:e=>{this.epoch===void 0?this.journal=void 0:e.type===`replace`?this.journal={epoch:this.epoch,cursor:e.entries.at(-1)?.event.seq??-1,records:[...e.entries],hasMore:e.hasMore}:this.journal!==void 0&&e.type===`append`?(this.journal.cursor=e.entry.event.seq,this.journal.records.push(e.entry)):this.journal!==void 0&&e.type===`prepend`&&(this.journal.records.unshift(...e.entries),this.journal.hasMore=e.hasMore),n.publish(de(e))},...n.carrierFailed===void 0?{}:{carrierFailed:n.carrierFailed},failed:n.failed}),this.remote=e,this.address=t,this.journal=r&&{...r,records:[...r.records]},this.epoch=r?.epoch}async*follow(e,t){let n,r=this.journal;for await(let a of this.remote.session.follow({address:this.address,assistantStream:!0,...this.repairRequest(e),...r===void 0?{}:{resume:{epoch:r.epoch,cursor:r.cursor}}},t))if(a.type===`snapshot`){for(let e of a.records)ue(e.event);if(a.assistantStream===void 0)throw new o(`gateway/internal`,`session assistant stream omitted its opted-in opening baseline`,{});let e=a.records,t=a.hasMore;if(a.resumedAfter!==void 0){if(r===void 0||a.epoch!==r.epoch||a.resumedAfter!==r.cursor||a.cursor!==(e.at(-1)?.event.seq??r.cursor)||e.length>0&&e[0]?.event.seq!==r.cursor+1)throw new o(`gateway/internal`,`Invalid session resume baseline`,{});e=[...r.records,...e],t=r.hasMore}let i=a.epoch!==void 0&&a.epoch!==this.epoch;this.epoch=a.epoch,n=a.assistantStream.revision,yield{type:`opened`,...i?{reset:!0}:{},cursor:a.cursor,page:{records:e,hasMore:t,projections:a.projections,assistantStream:a.assistantStream}}}else if(a.type===`assistant-stream`){let e=(n??0)+1;if(a.frame.revision!==e)throw new i.RemoteStreamCarrierError(`session assistant stream skipped revision ${String(e)}`);n=a.frame.revision,yield{type:`notification`,notification:a}}else a.type===`projection`?yield{type:`notification`,notification:a}:(ue(a.event),yield{type:`entry`,entry:a})}async readPage(e,t,n){let r=await this.remote.session.page({address:this.address,throughSeq:t,...e},n);if(!r.ok)throw r.error;for(let e of r.value.records)ue(e.event);return r.value}repairRequest(e){return{...e.maxMessages===void 0?{}:{maxMessages:e.maxMessages},...e.turnWindow===void 0?{}:{turnWindow:e.turnWindow}}}};function me(e){let t=e.replace(/[/\\]+$/,``),n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`));return t.slice(n+1)}let he=Symbol(`dsh.client.scope`);function ge(){}function _e(e,t){let n=e.plugin(ge),i={sessionId:t};return{fiber:n,ctx:n.ctx.extend({[he]:i,[r.Context.filter](e){let t=ye(e);return t===void 0||t===i}})}}function ve(e){return ye(e)?.sessionId}function ye(e){return e[he]}var be;let xe=/*@__PURE__*/ Object.freeze({status:`aborted`});function h(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:/* @__PURE__ */ new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var Se=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Ce=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(be=globalThis).__zod_globalConfig??(be.__zod_globalConfig={});let we=globalThis.__zod_globalConfig;function g(e){return e&&Object.assign(we,e),we}function Te(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Ee(e,t){return typeof t==`bigint`?t.toString():t}function De(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Oe(e){return e==null}function ke(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ae(e,t){let n=e/t,r=Math.round(n),i=2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}let je=/* @__PURE__*/ Symbol(`evaluating`);function _(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==je)return r===void 0&&(r=je,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Me(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ne(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Pe(e){return JSON.stringify(e)}function Fe(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}let Ie=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Le(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let Re=/* @__PURE__*/ De(()=>{if(we.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function ze(e){if(Le(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Le(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Be(e){return ze(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let Ve=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function He(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ue(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function v(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function We(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}let Ge={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ke(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Ue(e,Ne(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Me(this,`shape`,e),e},checks:[]}))}function qe(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Ue(e,Ne(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Me(this,`shape`,r),r},checks:[]}))}function Je(e,t){if(!ze(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ue(e,Ne(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Me(this,`shape`,n),n}}))}function Ye(e,t){if(!ze(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ue(e,Ne(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Me(this,`shape`,n),n}}))}function Xe(e,t){if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Ue(e,Ne(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Me(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Ze(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return Ue(t,Ne(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Me(this,`shape`,i),i},checks:[]}))}function Qe(e,t,n){return Ue(t,Ne(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Me(this,`shape`,i),i}}))}function $e(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function et(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function tt(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function nt(e){return typeof e==`string`?e:e?.message}function y(e,t,n){let r=e.message?e.message:nt(e.inst?._zod.def?.error?.(e))??nt(t?.error?.(e))??nt(n.customError?.(e))??nt(n.localeError?.(e))??`Invalid input`,{inst:i,continue:a,input:o,...s}=e;return s.path??=[],s.message=r,t?.reportInput&&(s.input=o),s}function rt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function it(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}let at=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Ee,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ot=h(`$ZodError`,at),st=h(`$ZodError`,at,{Parent:Error});function ct(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function lt(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i];i===e.length-1?(r[n]=r[n]||{_errors:[]},r[n]._errors.push(t(a))):r[n]=r[n]||{_errors:[]},r=r[n],i++}}}};return r(e),n}let ut=e=>(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Se;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>y(e,a,g())));throw Ie(t,i?.callee),t}return o.value},dt=e=>async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>y(e,a,g())));throw Ie(t,i?.callee),t}return o.value},ft=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Se;return a.issues.length?{success:!1,error:new(e??ot)(a.issues.map(e=>y(e,i,g())))}:{success:!0,data:a.value}},pt=/* @__PURE__*/ ft(st),mt=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>y(e,i,g())))}:{success:!0,data:a.value}},ht=/* @__PURE__*/ mt(st),gt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ut(e)(t,n,i)},_t=e=>(t,n,r)=>ut(e)(t,n,r),vt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return dt(e)(t,n,i)},yt=e=>async(t,n,r)=>dt(e)(t,n,r),bt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ft(e)(t,n,i)},xt=e=>(t,n,r)=>ft(e)(t,n,r),St=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return mt(e)(t,n,i)},Ct=e=>async(t,n,r)=>mt(e)(t,n,r),wt=/^[cC][0-9a-z]{6,}$/,Tt=/^[0-9a-z]+$/,Et=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dt=/^[0-9a-vA-V]{20}$/,Ot=/^[A-Za-z0-9]{27}$/,kt=/^[a-zA-Z0-9_-]{21}$/,At=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Mt=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Nt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Pt(){return RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)}let Ft=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,It=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Lt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Rt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bt=/^[A-Za-z0-9_-]*$/,Vt=/^https?$/,Ht=/^\+[1-9]\d{6,14}$/,Ut=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,Wt=/*@__PURE__*/ RegExp(`^${Ut}$`);function Gt(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Kt(e){return RegExp(`^${Gt(e)}$`)}function qt(e){let t=Gt({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${Ut}T(?:${r})$`)}let Jt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Yt=/^-?\d+$/,Xt=/^-?\d+(?:\.\d+)?$/,Zt=/^(?:true|false)$/i,Qt=/^null$/i,$t=/^[^A-Z]*$/,en=/^[^a-z]*$/,b=/*@__PURE__*/ h(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),tn={number:`number`,bigint:`bigint`,object:`date`},nn=/*@__PURE__*/ h(`$ZodCheckLessThan`,(e,t)=>{b.init(e,t);let n=tn[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rn=/*@__PURE__*/ h(`$ZodCheckGreaterThan`,(e,t)=>{b.init(e,t);let n=tn[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),an=/*@__PURE__*/ h(`$ZodCheckMultipleOf`,(e,t)=>{b.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Ae(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),on=/*@__PURE__*/ h(`$ZodCheckNumberFormat`,(e,t)=>{b.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ge[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Yt)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),sn=/*@__PURE__*/ h(`$ZodCheckMaxLength`,(e,t)=>{var n;b.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=rt(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),cn=/*@__PURE__*/ h(`$ZodCheckMinLength`,(e,t)=>{var n;b.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=rt(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ln=/*@__PURE__*/ h(`$ZodCheckLengthEquals`,(e,t)=>{var n;b.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Oe(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=rt(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),un=/*@__PURE__*/ h(`$ZodCheckStringFormat`,(e,t)=>{var n,r;b.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=/* @__PURE__ */ new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),dn=/*@__PURE__*/ h(`$ZodCheckRegex`,(e,t)=>{un.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),fn=/*@__PURE__*/ h(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=$t,un.init(e,t)}),pn=/*@__PURE__*/ h(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=en,un.init(e,t)}),mn=/*@__PURE__*/ h(`$ZodCheckIncludes`,(e,t)=>{b.init(e,t);let n=He(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),hn=/*@__PURE__*/ h(`$ZodCheckStartsWith`,(e,t)=>{b.init(e,t);let n=RegExp(`^${He(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),gn=/*@__PURE__*/ h(`$ZodCheckEndsWith`,(e,t)=>{b.init(e,t);let n=RegExp(`.*${He(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=/* @__PURE__ */ new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),_n=/*@__PURE__*/ h(`$ZodCheckOverwrite`,(e,t)=>{b.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var vn=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
2
2
  `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
3
- `))}};let vn={major:4,minor:4,patch:3},S=/*@__PURE__*/ h(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=vn;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=$e(e),i;for(let a of t){if(a._zod.def.when){if(et(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Se;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=$e(e,t))});else{if(e.issues.length===t)continue;r||=$e(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if($e(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Se;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Se;return o.then(e=>t(e,r,a))}return t(o,r,a)}}_(e,`~standard`,()=>({validate:t=>{try{let n=ft(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return mt(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),yn=/*@__PURE__*/ h(`$ZodString`,(e,t)=>{S.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??qt(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),C=/*@__PURE__*/ h(`$ZodStringFormat`,(e,t)=>{ln.init(e,t),yn.init(e,t)}),bn=/*@__PURE__*/ h(`$ZodGUID`,(e,t)=>{t.pattern??=At,C.init(e,t)}),xn=/*@__PURE__*/ h(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=jt(e)}else t.pattern??=jt();C.init(e,t)}),Sn=/*@__PURE__*/ h(`$ZodEmail`,(e,t)=>{t.pattern??=Mt,C.init(e,t)}),Cn=/*@__PURE__*/ h(`$ZodURL`,(e,t)=>{C.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Bt.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),wn=/*@__PURE__*/ h(`$ZodEmoji`,(e,t)=>{t.pattern??=Nt(),C.init(e,t)}),Tn=/*@__PURE__*/ h(`$ZodNanoID`,(e,t)=>{t.pattern??=Ot,C.init(e,t)}),En=/*@__PURE__*/ h(`$ZodCUID`,(e,t)=>{t.pattern??=Ct,C.init(e,t)}),Dn=/*@__PURE__*/ h(`$ZodCUID2`,(e,t)=>{t.pattern??=wt,C.init(e,t)}),On=/*@__PURE__*/ h(`$ZodULID`,(e,t)=>{t.pattern??=Tt,C.init(e,t)}),kn=/*@__PURE__*/ h(`$ZodXID`,(e,t)=>{t.pattern??=Et,C.init(e,t)}),An=/*@__PURE__*/ h(`$ZodKSUID`,(e,t)=>{t.pattern??=Dt,C.init(e,t)}),jn=/*@__PURE__*/ h(`$ZodISODateTime`,(e,t)=>{t.pattern??=Kt(t),C.init(e,t)}),Mn=/*@__PURE__*/ h(`$ZodISODate`,(e,t)=>{t.pattern??=Ut,C.init(e,t)}),Nn=/*@__PURE__*/ h(`$ZodISOTime`,(e,t)=>{t.pattern??=Gt(t),C.init(e,t)}),Pn=/*@__PURE__*/ h(`$ZodISODuration`,(e,t)=>{t.pattern??=kt,C.init(e,t)}),Fn=/*@__PURE__*/ h(`$ZodIPv4`,(e,t)=>{t.pattern??=Pt,C.init(e,t),e._zod.bag.format=`ipv4`}),In=/*@__PURE__*/ h(`$ZodIPv6`,(e,t)=>{t.pattern??=Ft,C.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Ln=/*@__PURE__*/ h(`$ZodCIDRv4`,(e,t)=>{t.pattern??=It,C.init(e,t)}),Rn=/*@__PURE__*/ h(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Lt,C.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function zn(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let Bn=/*@__PURE__*/ h(`$ZodBase64`,(e,t)=>{t.pattern??=Rt,C.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{zn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Vn(e){if(!zt.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return zn(t.padEnd(Math.ceil(t.length/4)*4,`=`))}let Hn=/*@__PURE__*/ h(`$ZodBase64URL`,(e,t)=>{t.pattern??=zt,C.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Vn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Un=/*@__PURE__*/ h(`$ZodE164`,(e,t)=>{t.pattern??=Vt,C.init(e,t)});function Wn(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}let Gn=/*@__PURE__*/ h(`$ZodJWT`,(e,t)=>{C.init(e,t),e._zod.check=n=>{Wn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Kn=/*@__PURE__*/ h(`$ZodNumber`,(e,t)=>{S.init(e,t),e._zod.pattern=e._zod.bag.pattern??Yt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),qn=/*@__PURE__*/ h(`$ZodNumberFormat`,(e,t)=>{an.init(e,t),Kn.init(e,t)}),Jn=/*@__PURE__*/ h(`$ZodBoolean`,(e,t)=>{S.init(e,t),e._zod.pattern=Xt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Yn=/*@__PURE__*/ h(`$ZodNull`,(e,t)=>{S.init(e,t),e._zod.pattern=Zt,e._zod.values=/* @__PURE__ */ new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Xn=/*@__PURE__*/ h(`$ZodUnknown`,(e,t)=>{S.init(e,t),e._zod.parse=e=>e}),Zn=/*@__PURE__*/ h(`$ZodNever`,(e,t)=>{S.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Qn(e,t,n){e.issues.length&&t.issues.push(...y(n,e.issues)),t.value[n]=e.value}let $n=/*@__PURE__*/ h(`$ZodArray`,(e,t)=>{S.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>Qn(t,n,e))):Qn(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function er(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...y(n,e.issues))}!o&&!i?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function tr(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=We(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function nr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>er(e,n,i,t,u,d))):er(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}let rr=/*@__PURE__*/ h(`$ZodObject`,(e,t)=>{if(S.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=De(()=>tr(t));_(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */ new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Le,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>er(n,t,e,s,r,i))):er(a,t,e,s,r,i)}return i?nr(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),ir=/*@__PURE__*/ h(`$ZodObjectJIT`,(e,t)=>{rr.init(e,t);let n=e._zod.parse,r=De(()=>tr(t)),i=e=>{let t=new _n([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Pe(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Pe(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
3
+ `))}};let yn={major:4,minor:4,patch:3},x=/*@__PURE__*/ h(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=yn;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=$e(e),i;for(let a of t){if(a._zod.def.when){if(et(e)||!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Se;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=$e(e,t))});else{if(e.issues.length===t)continue;r||=$e(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if($e(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Se;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Se;return o.then(e=>t(e,r,a))}return t(o,r,a)}}_(e,`~standard`,()=>({validate:t=>{try{let n=pt(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return ht(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),bn=/*@__PURE__*/ h(`$ZodString`,(e,t)=>{x.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Jt(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),S=/*@__PURE__*/ h(`$ZodStringFormat`,(e,t)=>{un.init(e,t),bn.init(e,t)}),xn=/*@__PURE__*/ h(`$ZodGUID`,(e,t)=>{t.pattern??=jt,S.init(e,t)}),Sn=/*@__PURE__*/ h(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Mt(e)}else t.pattern??=Mt();S.init(e,t)}),Cn=/*@__PURE__*/ h(`$ZodEmail`,(e,t)=>{t.pattern??=Nt,S.init(e,t)}),wn=/*@__PURE__*/ h(`$ZodURL`,(e,t)=>{S.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Vt.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}let i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Tn=/*@__PURE__*/ h(`$ZodEmoji`,(e,t)=>{t.pattern??=Pt(),S.init(e,t)}),En=/*@__PURE__*/ h(`$ZodNanoID`,(e,t)=>{t.pattern??=kt,S.init(e,t)}),Dn=/*@__PURE__*/ h(`$ZodCUID`,(e,t)=>{t.pattern??=wt,S.init(e,t)}),On=/*@__PURE__*/ h(`$ZodCUID2`,(e,t)=>{t.pattern??=Tt,S.init(e,t)}),kn=/*@__PURE__*/ h(`$ZodULID`,(e,t)=>{t.pattern??=Et,S.init(e,t)}),An=/*@__PURE__*/ h(`$ZodXID`,(e,t)=>{t.pattern??=Dt,S.init(e,t)}),jn=/*@__PURE__*/ h(`$ZodKSUID`,(e,t)=>{t.pattern??=Ot,S.init(e,t)}),Mn=/*@__PURE__*/ h(`$ZodISODateTime`,(e,t)=>{t.pattern??=qt(t),S.init(e,t)}),Nn=/*@__PURE__*/ h(`$ZodISODate`,(e,t)=>{t.pattern??=Wt,S.init(e,t)}),Pn=/*@__PURE__*/ h(`$ZodISOTime`,(e,t)=>{t.pattern??=Kt(t),S.init(e,t)}),Fn=/*@__PURE__*/ h(`$ZodISODuration`,(e,t)=>{t.pattern??=At,S.init(e,t)}),In=/*@__PURE__*/ h(`$ZodIPv4`,(e,t)=>{t.pattern??=Ft,S.init(e,t),e._zod.bag.format=`ipv4`}),Ln=/*@__PURE__*/ h(`$ZodIPv6`,(e,t)=>{t.pattern??=It,S.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),Rn=/*@__PURE__*/ h(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Lt,S.init(e,t)}),zn=/*@__PURE__*/ h(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Rt,S.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}});function Bn(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let Vn=/*@__PURE__*/ h(`$ZodBase64`,(e,t)=>{t.pattern??=zt,S.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Bn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Hn(e){if(!Bt.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Bn(t.padEnd(Math.ceil(t.length/4)*4,`=`))}let Un=/*@__PURE__*/ h(`$ZodBase64URL`,(e,t)=>{t.pattern??=Bt,S.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Hn(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Wn=/*@__PURE__*/ h(`$ZodE164`,(e,t)=>{t.pattern??=Ht,S.init(e,t)});function Gn(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}let Kn=/*@__PURE__*/ h(`$ZodJWT`,(e,t)=>{S.init(e,t),e._zod.check=n=>{Gn(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),qn=/*@__PURE__*/ h(`$ZodNumber`,(e,t)=>{x.init(e,t),e._zod.pattern=e._zod.bag.pattern??Xt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Jn=/*@__PURE__*/ h(`$ZodNumberFormat`,(e,t)=>{on.init(e,t),qn.init(e,t)}),Yn=/*@__PURE__*/ h(`$ZodBoolean`,(e,t)=>{x.init(e,t),e._zod.pattern=Zt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Xn=/*@__PURE__*/ h(`$ZodNull`,(e,t)=>{x.init(e,t),e._zod.pattern=Qt,e._zod.values=/* @__PURE__ */ new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Zn=/*@__PURE__*/ h(`$ZodUnknown`,(e,t)=>{x.init(e,t),e._zod.parse=e=>e}),Qn=/*@__PURE__*/ h(`$ZodNever`,(e,t)=>{x.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function $n(e,t,n){e.issues.length&&t.issues.push(...tt(n,e.issues)),t.value[n]=e.value}let er=/*@__PURE__*/ h(`$ZodArray`,(e,t)=>{x.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>$n(t,n,e))):$n(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function tr(e,t,n,r,i,a){let o=n in r;if(e.issues.length){if(i&&a&&!o)return;t.issues.push(...tt(n,e.issues))}!o&&!i?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function nr(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=We(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function rr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin===`optional`,d=c.optout===`optional`;for(let i in t){if(i===`__proto__`||s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>tr(e,n,i,t,u,d))):tr(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}let ir=/*@__PURE__*/ h(`$ZodObject`,(e,t)=>{if(x.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=De(()=>nr(t));_(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */ new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Le,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optin===`optional`,i=n._zod.optout===`optional`,a=n._zod.run({value:s[e],issues:[]},o);a instanceof Promise?c.push(a.then(n=>tr(n,t,e,s,r,i))):tr(a,t,e,s,r,i)}return i?rr(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),ar=/*@__PURE__*/ h(`$ZodObjectJIT`,(e,t)=>{ir.init(e,t);let n=e._zod.parse,r=De(()=>nr(t)),i=e=>{let t=new vn([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=Pe(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=Pe(r),s=e[r],c=s?._zod?.optin===`optional`,l=s?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),c&&l?t.write(`
4
4
  if (${n}.issues.length) {
5
5
  if (${o} in input) {
6
6
  payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
@@ -59,82 +59,82 @@ window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,facto
59
59
  }
60
60
  }
61
61
 
62
- `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Le,s=!we.jitless,c=s&&Re.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?nr([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function ar(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!$e(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>b(e,r,g())))}),t)}let or=/*@__PURE__*/ h(`$ZodUnion`,(e,t)=>{S.init(e,t),_(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),_(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),_(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),_(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>ke(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>ar(t,r,e,i)):ar(o,r,e,i)}}),sr=/*@__PURE__*/ h(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,or.init(e,t);let n=e._zod.parse;_(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=/* @__PURE__ */ new Set);for(let r of n)e[t].add(r)}}return e});let r=De(()=>{let e=t.options,n=/* @__PURE__ */ new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Le(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),cr=/*@__PURE__*/ h(`$ZodIntersection`,(e,t)=>{S.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>ur(e,t,n)):ur(e,i,a)}});function lr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ze(e)&&ze(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=lr(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=lr(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function ur(e,t,n){let r=/* @__PURE__ */ new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),$e(e))return e;let o=lr(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let dr=/*@__PURE__*/ h(`$ZodTuple`,(e,t)=>{S.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=fr(n,`optin`),c=fr(n,`optout`);if(!t.rest){if(a.length<s)return r.issues.push({code:`too_small`,minimum:s,inclusive:!0,input:a,inst:e,origin:`array`}),r;a.length>n.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:a[e],issues:[]},i);t instanceof Promise?o.push(t.then(t=>{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>pr(t,r,e))):pr(a,r,e)}}return o.length?Promise.all(o).then(()=>mr(l,r,n,a,c)):mr(l,r,n,a,c)}});function fr(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function pr(e,t,n){e.issues.length&&t.issues.push(...y(n,e.issues)),t.value[n]=e.value}function mr(e,t,n,r,i){for(let a=0;a<n.length;a++){let n=e[a],o=a<r.length;if(n.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...y(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}let hr=/*@__PURE__*/ h(`$ZodRecord`,(e,t)=>{S.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!ze(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=/* @__PURE__ */ new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>b(e,r,g())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...y(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...y(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Yt.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>b(e,r,g())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...y(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...y(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),gr=/*@__PURE__*/ h(`$ZodEnum`,(e,t)=>{S.init(e,t);let n=Te(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Ve.has(typeof e)).map(e=>typeof e==`string`?He(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),_r=/*@__PURE__*/ h(`$ZodLiteral`,(e,t)=>{if(S.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?He(e):e?He(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),vr=/*@__PURE__*/ h(`$ZodTransform`,(e,t)=>{S.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Se;return n.value=i,n.fallback=!0,n}});function yr(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let br=/*@__PURE__*/ h(`$ZodOptional`,(e,t)=>{S.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,_(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,void 0]):void 0),_(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ke(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>yr(e,r)):yr(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),xr=/*@__PURE__*/ h(`$ZodExactOptional`,(e,t)=>{br.init(e,t),_(e._zod,`values`,()=>t.innerType._zod.values),_(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Sr=/*@__PURE__*/ h(`$ZodNullable`,(e,t)=>{S.init(e,t),_(e._zod,`optin`,()=>t.innerType._zod.optin),_(e._zod,`optout`,()=>t.innerType._zod.optout),_(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ke(e.source)}|null)$`):void 0}),_(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Cr=/*@__PURE__*/ h(`$ZodDefault`,(e,t)=>{S.init(e,t),e._zod.optin=`optional`,_(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>wr(e,t)):wr(r,t)}});function wr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let Tr=/*@__PURE__*/ h(`$ZodPrefault`,(e,t)=>{S.init(e,t),e._zod.optin=`optional`,_(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Er=/*@__PURE__*/ h(`$ZodNonOptional`,(e,t)=>{S.init(e,t),_(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Dr(t,e)):Dr(i,e)}});function Dr(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}let Or=/*@__PURE__*/ h(`$ZodCatch`,(e,t)=>{S.init(e,t),e._zod.optin=`optional`,_(e._zod,`optout`,()=>t.innerType._zod.optout),_(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>b(e,n,g()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>b(e,n,g()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),kr=/*@__PURE__*/ h(`$ZodPipe`,(e,t)=>{S.init(e,t),_(e._zod,`values`,()=>t.in._zod.values),_(e._zod,`optin`,()=>t.in._zod.optin),_(e._zod,`optout`,()=>t.out._zod.optout),_(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ar(e,t.in,n)):Ar(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ar(e,t.out,n)):Ar(r,t.out,n)}});function Ar(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}let jr=/*@__PURE__*/ h(`$ZodReadonly`,(e,t)=>{S.init(e,t),_(e._zod,`propValues`,()=>t.innerType._zod.propValues),_(e._zod,`values`,()=>t.innerType._zod.values),_(e._zod,`optin`,()=>t.innerType?._zod?.optin),_(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Mr):Mr(r)}});function Mr(e){return e.value=Object.freeze(e.value),e}let Nr=/*@__PURE__*/ h(`$ZodLazy`,(e,t)=>{S.init(e,t),_(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),_(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),_(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),_(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),_(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Pr=/*@__PURE__*/ h(`$ZodCustom`,(e,t)=>{x.init(e,t),S.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Fr(t,n,r,e));Fr(i,n,r,e)}});function Fr(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(rt(e))}}var Ir,Lr=class{constructor(){this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Rr(){return new Lr}(Ir=globalThis).__zod_globalRegistry??(Ir.__zod_globalRegistry=Rr());let zr=globalThis.__zod_globalRegistry;// @__NO_SIDE_EFFECTS__
63
- function Br(e,t){return new e({type:`string`,...v(t)})}// @__NO_SIDE_EFFECTS__
64
- function Vr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
65
- function Hr(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
66
- function Ur(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
67
- function Wr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...v(t)})}// @__NO_SIDE_EFFECTS__
68
- function Gr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...v(t)})}// @__NO_SIDE_EFFECTS__
69
- function Kr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...v(t)})}// @__NO_SIDE_EFFECTS__
70
- function qr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
71
- function Jr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
72
- function Yr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
73
- function Xr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
74
- function Zr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
75
- function Qr(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
76
- function $r(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
77
- function ei(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
78
- function ti(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
79
- function ni(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
80
- function ri(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
81
- function ii(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
82
- function ai(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
83
- function oi(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
84
- function si(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
85
- function ci(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
86
- function li(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...v(t)})}// @__NO_SIDE_EFFECTS__
87
- function ui(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...v(t)})}// @__NO_SIDE_EFFECTS__
88
- function di(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...v(t)})}// @__NO_SIDE_EFFECTS__
89
- function fi(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...v(t)})}// @__NO_SIDE_EFFECTS__
90
- function pi(e,t){return new e({type:`number`,checks:[],...v(t)})}// @__NO_SIDE_EFFECTS__
91
- function mi(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...v(t)})}// @__NO_SIDE_EFFECTS__
92
- function hi(e,t){return new e({type:`boolean`,...v(t)})}// @__NO_SIDE_EFFECTS__
93
- function gi(e,t){return new e({type:`null`,...v(t)})}// @__NO_SIDE_EFFECTS__
94
- function _i(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
95
- function vi(e,t){return new e({type:`never`,...v(t)})}// @__NO_SIDE_EFFECTS__
96
- function yi(e,t){return new tn({check:`less_than`,...v(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
97
- function bi(e,t){return new tn({check:`less_than`,...v(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
98
- function xi(e,t){return new nn({check:`greater_than`,...v(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
99
- function Si(e,t){return new nn({check:`greater_than`,...v(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
100
- function Ci(e,t){return new rn({check:`multiple_of`,...v(t),value:e})}// @__NO_SIDE_EFFECTS__
101
- function wi(e,t){return new on({check:`max_length`,...v(t),maximum:e})}// @__NO_SIDE_EFFECTS__
102
- function Ti(e,t){return new sn({check:`min_length`,...v(t),minimum:e})}// @__NO_SIDE_EFFECTS__
103
- function Ei(e,t){return new cn({check:`length_equals`,...v(t),length:e})}// @__NO_SIDE_EFFECTS__
104
- function Di(e,t){return new un({check:`string_format`,format:`regex`,...v(t),pattern:e})}// @__NO_SIDE_EFFECTS__
105
- function Oi(e){return new dn({check:`string_format`,format:`lowercase`,...v(e)})}// @__NO_SIDE_EFFECTS__
106
- function ki(e){return new fn({check:`string_format`,format:`uppercase`,...v(e)})}// @__NO_SIDE_EFFECTS__
107
- function Ai(e,t){return new pn({check:`string_format`,format:`includes`,...v(t),includes:e})}// @__NO_SIDE_EFFECTS__
108
- function ji(e,t){return new mn({check:`string_format`,format:`starts_with`,...v(t),prefix:e})}// @__NO_SIDE_EFFECTS__
109
- function Mi(e,t){return new hn({check:`string_format`,format:`ends_with`,...v(t),suffix:e})}// @__NO_SIDE_EFFECTS__
110
- function Ni(e){return new gn({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
111
- function Pi(e){return/* @__PURE__ */ Ni(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
112
- function Fi(){return/* @__PURE__ */ Ni(e=>e.trim())}// @__NO_SIDE_EFFECTS__
113
- function Ii(){return/* @__PURE__ */ Ni(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
114
- function Li(){return/* @__PURE__ */ Ni(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
115
- function Ri(){return/* @__PURE__ */ Ni(e=>Fe(e))}// @__NO_SIDE_EFFECTS__
116
- function zi(e,t,n){return new e({type:`array`,element:t,...v(n)})}// @__NO_SIDE_EFFECTS__
117
- function Bi(e,t,n){let r=v(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
118
- function Vi(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...v(n)})}// @__NO_SIDE_EFFECTS__
119
- function Hi(e,t){let n=/* @__PURE__ */ Ui(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(rt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(rt(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
120
- function Ui(e,t){let n=new x({check:`custom`,...v(t)});return n._zod.check=e,n}function Wi(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??zr,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function w(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,w(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&T(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Gi(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
62
+ `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=Le,s=!we.jitless,c=s&&Re.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?rr([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function or(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!$e(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>y(e,r,g())))}),t)}let sr=/*@__PURE__*/ h(`$ZodUnion`,(e,t)=>{x.init(e,t),_(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),_(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),_(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),_(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>ke(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>or(t,r,e,i)):or(o,r,e,i)}}),cr=/*@__PURE__*/ h(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,sr.init(e,t);let n=e._zod.parse;_(e._zod,`propValues`,()=>{let e={};for(let n of t.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(let[t,n]of Object.entries(r)){e[t]||(e[t]=/* @__PURE__ */ new Set);for(let r of n)e[t].add(r)}}return e});let r=De(()=>{let e=t.options,n=/* @__PURE__ */ new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Le(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),lr=/*@__PURE__*/ h(`$ZodIntersection`,(e,t)=>{x.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>dr(e,t,n)):dr(e,i,a)}});function ur(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(ze(e)&&ze(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=ur(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=ur(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function dr(e,t,n){let r=/* @__PURE__ */ new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),$e(e))return e;let o=ur(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}let fr=/*@__PURE__*/ h(`$ZodTuple`,(e,t)=>{x.init(e,t);let n=t.items;e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({input:a,inst:e,expected:`tuple`,code:`invalid_type`}),r;r.value=[];let o=[],s=pr(n,`optin`),c=pr(n,`optout`);if(!t.rest){if(a.length<s)return r.issues.push({code:`too_small`,minimum:s,inclusive:!0,input:a,inst:e,origin:`array`}),r;a.length>n.length&&r.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:a,inst:e,origin:`array`})}let l=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:a[e],issues:[]},i);t instanceof Promise?o.push(t.then(t=>{l[e]=t})):l[e]=t}if(t.rest){let e=n.length-1,s=a.slice(n.length);for(let n of s){e++;let a=t.rest._zod.run({value:n,issues:[]},i);a instanceof Promise?o.push(a.then(t=>mr(t,r,e))):mr(a,r,e)}}return o.length?Promise.all(o).then(()=>hr(l,r,n,a,c)):hr(l,r,n,a,c)}});function pr(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!==`optional`)return n+1;return 0}function mr(e,t,n){e.issues.length&&t.issues.push(...tt(n,e.issues)),t.value[n]=e.value}function hr(e,t,n,r,i){for(let a=0;a<n.length;a++){let n=e[a],o=a<r.length;if(n.issues.length){if(!o&&a>=i){t.value.length=a;break}t.issues.push(...tt(a,n.issues))}t.value[a]=n.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}let gr=/*@__PURE__*/ h(`$ZodRecord`,(e,t)=>{x.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!ze(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=/* @__PURE__ */ new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>y(e,r,g())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...tt(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...tt(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Xt.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>y(e,r,g())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...tt(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...tt(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),_r=/*@__PURE__*/ h(`$ZodEnum`,(e,t)=>{x.init(e,t);let n=Te(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>Ve.has(typeof e)).map(e=>typeof e==`string`?He(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),vr=/*@__PURE__*/ h(`$ZodLiteral`,(e,t)=>{if(x.init(e,t),t.values.length===0)throw Error(`Cannot create literal schema with no valid values`);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?He(e):e?He(e.toString()):String(e)).join(`|`)})$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),yr=/*@__PURE__*/ h(`$ZodTransform`,(e,t)=>{x.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Se;return n.value=i,n.fallback=!0,n}});function br(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}let xr=/*@__PURE__*/ h(`$ZodOptional`,(e,t)=>{x.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,_(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,void 0]):void 0),_(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ke(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>br(e,r)):br(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Sr=/*@__PURE__*/ h(`$ZodExactOptional`,(e,t)=>{xr.init(e,t),_(e._zod,`values`,()=>t.innerType._zod.values),_(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Cr=/*@__PURE__*/ h(`$ZodNullable`,(e,t)=>{x.init(e,t),_(e._zod,`optin`,()=>t.innerType._zod.optin),_(e._zod,`optout`,()=>t.innerType._zod.optout),_(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${ke(e.source)}|null)$`):void 0}),_(e._zod,`values`,()=>t.innerType._zod.values?/* @__PURE__ */ new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),wr=/*@__PURE__*/ h(`$ZodDefault`,(e,t)=>{x.init(e,t),e._zod.optin=`optional`,_(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Tr(e,t)):Tr(r,t)}});function Tr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let Er=/*@__PURE__*/ h(`$ZodPrefault`,(e,t)=>{x.init(e,t),e._zod.optin=`optional`,_(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Dr=/*@__PURE__*/ h(`$ZodNonOptional`,(e,t)=>{x.init(e,t),_(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Or(t,e)):Or(i,e)}});function Or(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}let kr=/*@__PURE__*/ h(`$ZodCatch`,(e,t)=>{x.init(e,t),e._zod.optin=`optional`,_(e._zod,`optout`,()=>t.innerType._zod.optout),_(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>y(e,n,g()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>y(e,n,g()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Ar=/*@__PURE__*/ h(`$ZodPipe`,(e,t)=>{x.init(e,t),_(e._zod,`values`,()=>t.in._zod.values),_(e._zod,`optin`,()=>t.in._zod.optin),_(e._zod,`optout`,()=>t.out._zod.optout),_(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>jr(e,t.in,n)):jr(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>jr(e,t.out,n)):jr(r,t.out,n)}});function jr(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}let Mr=/*@__PURE__*/ h(`$ZodReadonly`,(e,t)=>{x.init(e,t),_(e._zod,`propValues`,()=>t.innerType._zod.propValues),_(e._zod,`values`,()=>t.innerType._zod.values),_(e._zod,`optin`,()=>t.innerType?._zod?.optin),_(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Nr):Nr(r)}});function Nr(e){return e.value=Object.freeze(e.value),e}let Pr=/*@__PURE__*/ h(`$ZodLazy`,(e,t)=>{x.init(e,t),_(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),_(e._zod,`pattern`,()=>e._zod.innerType?._zod?.pattern),_(e._zod,`propValues`,()=>e._zod.innerType?._zod?.propValues),_(e._zod,`optin`,()=>e._zod.innerType?._zod?.optin??void 0),_(e._zod,`optout`,()=>e._zod.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Fr=/*@__PURE__*/ h(`$ZodCustom`,(e,t)=>{b.init(e,t),x.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ir(t,n,r,e));Ir(i,n,r,e)}});function Ir(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(it(e))}}var Lr,Rr=class{constructor(){this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function zr(){return new Rr}(Lr=globalThis).__zod_globalRegistry??(Lr.__zod_globalRegistry=zr());let Br=globalThis.__zod_globalRegistry;// @__NO_SIDE_EFFECTS__
63
+ function Vr(e,t){return new e({type:`string`,...v(t)})}// @__NO_SIDE_EFFECTS__
64
+ function Hr(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
65
+ function Ur(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
66
+ function Wr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
67
+ function Gr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...v(t)})}// @__NO_SIDE_EFFECTS__
68
+ function Kr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...v(t)})}// @__NO_SIDE_EFFECTS__
69
+ function qr(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...v(t)})}// @__NO_SIDE_EFFECTS__
70
+ function Jr(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
71
+ function Yr(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
72
+ function Xr(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
73
+ function Zr(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
74
+ function Qr(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
75
+ function $r(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
76
+ function ei(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
77
+ function ti(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
78
+ function ni(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
79
+ function ri(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
80
+ function ii(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
81
+ function ai(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
82
+ function oi(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
83
+ function si(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
84
+ function ci(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
85
+ function li(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...v(t)})}// @__NO_SIDE_EFFECTS__
86
+ function ui(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...v(t)})}// @__NO_SIDE_EFFECTS__
87
+ function di(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...v(t)})}// @__NO_SIDE_EFFECTS__
88
+ function fi(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...v(t)})}// @__NO_SIDE_EFFECTS__
89
+ function pi(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...v(t)})}// @__NO_SIDE_EFFECTS__
90
+ function mi(e,t){return new e({type:`number`,checks:[],...v(t)})}// @__NO_SIDE_EFFECTS__
91
+ function hi(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...v(t)})}// @__NO_SIDE_EFFECTS__
92
+ function gi(e,t){return new e({type:`boolean`,...v(t)})}// @__NO_SIDE_EFFECTS__
93
+ function _i(e,t){return new e({type:`null`,...v(t)})}// @__NO_SIDE_EFFECTS__
94
+ function vi(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
95
+ function yi(e,t){return new e({type:`never`,...v(t)})}// @__NO_SIDE_EFFECTS__
96
+ function bi(e,t){return new nn({check:`less_than`,...v(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
97
+ function xi(e,t){return new nn({check:`less_than`,...v(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
98
+ function Si(e,t){return new rn({check:`greater_than`,...v(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
99
+ function Ci(e,t){return new rn({check:`greater_than`,...v(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
100
+ function wi(e,t){return new an({check:`multiple_of`,...v(t),value:e})}// @__NO_SIDE_EFFECTS__
101
+ function Ti(e,t){return new sn({check:`max_length`,...v(t),maximum:e})}// @__NO_SIDE_EFFECTS__
102
+ function Ei(e,t){return new cn({check:`min_length`,...v(t),minimum:e})}// @__NO_SIDE_EFFECTS__
103
+ function Di(e,t){return new ln({check:`length_equals`,...v(t),length:e})}// @__NO_SIDE_EFFECTS__
104
+ function Oi(e,t){return new dn({check:`string_format`,format:`regex`,...v(t),pattern:e})}// @__NO_SIDE_EFFECTS__
105
+ function ki(e){return new fn({check:`string_format`,format:`lowercase`,...v(e)})}// @__NO_SIDE_EFFECTS__
106
+ function Ai(e){return new pn({check:`string_format`,format:`uppercase`,...v(e)})}// @__NO_SIDE_EFFECTS__
107
+ function ji(e,t){return new mn({check:`string_format`,format:`includes`,...v(t),includes:e})}// @__NO_SIDE_EFFECTS__
108
+ function Mi(e,t){return new hn({check:`string_format`,format:`starts_with`,...v(t),prefix:e})}// @__NO_SIDE_EFFECTS__
109
+ function Ni(e,t){return new gn({check:`string_format`,format:`ends_with`,...v(t),suffix:e})}// @__NO_SIDE_EFFECTS__
110
+ function Pi(e){return new _n({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
111
+ function Fi(e){return/* @__PURE__ */ Pi(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
112
+ function Ii(){return/* @__PURE__ */ Pi(e=>e.trim())}// @__NO_SIDE_EFFECTS__
113
+ function Li(){return/* @__PURE__ */ Pi(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
114
+ function Ri(){return/* @__PURE__ */ Pi(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
115
+ function zi(){return/* @__PURE__ */ Pi(e=>Fe(e))}// @__NO_SIDE_EFFECTS__
116
+ function Bi(e,t,n){return new e({type:`array`,element:t,...v(n)})}// @__NO_SIDE_EFFECTS__
117
+ function Vi(e,t,n){let r=v(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
118
+ function Hi(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...v(n)})}// @__NO_SIDE_EFFECTS__
119
+ function Ui(e,t){let n=/* @__PURE__ */ Wi(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(it(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(it(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
120
+ function Wi(e,t){let n=new b({check:`custom`,...v(t)});return n._zod.check=e,n}function Gi(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Br,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function C(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,C(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&w(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Ki(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
121
121
 
122
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}}function Ki(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Ji(t,`input`,e.processors),output:Ji(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function T(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return T(r.element,n);if(r.type===`set`)return T(r.valueType,n);if(r.type===`lazy`)return T(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return T(r.innerType,n);if(r.type===`intersection`)return T(r.left,n)||T(r.right,n);if(r.type===`record`||r.type===`map`)return T(r.keyType,n)||T(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:T(r.in,n)||T(r.out,n);if(r.type===`object`){for(let e in r.shape)if(T(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(T(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(T(e,n))return!0;return!!(r.rest&&T(r.rest,n))}return!1}let qi=(e,t={})=>n=>{let r=Wi({...n,processors:t});return w(e,r),Gi(r,e),Ki(r,e)},Ji=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Wi({...i??{},target:a,io:t,processors:n});return w(e,o),Gi(o,e),Ki(o,e)},Yi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Xi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Yi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Zi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},Qi=(e,t,n,r)=>{n.type=`boolean`},$i=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ea=(e,t,n,r)=>{n.not={}},ta=(e,t,n,r)=>{let i=e._zod.def,a=Te(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},na=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ra=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},ia=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},aa=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=w(a.element,t,{...r,path:[...r.path,`items`]})},oa=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=w(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=w(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},sa=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>w(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},ca=(e,t,n,r)=>{let i=e._zod.def,a=w(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=w(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},la=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>w(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?w(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},ua=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=w(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=w(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=w(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},da=(e,t,n,r)=>{let i=e._zod.def,a=w(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},fa=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},pa=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},ma=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},ha=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},ga=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;w(o,t,r);let s=t.seen.get(e);s.ref=o},_a=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},va=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ya=(e,t,n,r)=>{let i=e._zod.innerType;w(i,t,r);let a=t.seen.get(e);a.ref=i},ba=/*@__PURE__*/ h(`ZodISODateTime`,(e,t)=>{jn.init(e,t),k.init(e,t)});function xa(e){return/* @__PURE__ */ li(ba,e)}let Sa=/*@__PURE__*/ h(`ZodISODate`,(e,t)=>{Mn.init(e,t),k.init(e,t)});function Ca(e){return/* @__PURE__ */ ui(Sa,e)}let wa=/*@__PURE__*/ h(`ZodISOTime`,(e,t)=>{Nn.init(e,t),k.init(e,t)});function Ta(e){return/* @__PURE__ */ di(wa,e)}let Ea=/*@__PURE__*/ h(`ZodISODuration`,(e,t)=>{Pn.init(e,t),k.init(e,t)});function Da(e){return/* @__PURE__ */ fi(Ea,e)}let E=/*@__PURE__*/ h(`ZodError`,(e,t)=>{at.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>ct(e,t)},flatten:{value:t=>st(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ee,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ee,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),Oa=/* @__PURE__ */ lt(E),ka=/* @__PURE__ */ ut(E),Aa=/* @__PURE__ */ dt(E),ja=/* @__PURE__ */ pt(E),Ma=/* @__PURE__ */ ht(E),Na=/* @__PURE__ */ gt(E),Pa=/* @__PURE__ */ _t(E),Fa=/* @__PURE__ */ vt(E),Ia=/* @__PURE__ */ yt(E),La=/* @__PURE__ */ bt(E),Ra=/* @__PURE__ */ xt(E),za=/* @__PURE__ */ St(E),Ba=/* @__PURE__ */ new WeakMap;function Va(e,t,n){let r=Object.getPrototypeOf(e),i=Ba.get(r);if(i||(i=/* @__PURE__ */ new Set,Ba.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let D=/*@__PURE__*/ h(`ZodType`,(e,t)=>(S.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Ji(e,`input`),output:Ji(e,`output`)}}),e.toJSONSchema=qi(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>Oa(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Aa(e,t,n),e.parseAsync=async(t,n)=>ka(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ja(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ma(e,t,n),e.decode=(t,n)=>Na(e,t,n),e.encodeAsync=async(t,n)=>Pa(e,t,n),e.decodeAsync=async(t,n)=>Fa(e,t,n),e.safeEncode=(t,n)=>Ia(e,t,n),e.safeDecode=(t,n)=>La(e,t,n),e.safeEncodeAsync=async(t,n)=>Ra(e,t,n),e.safeDecodeAsync=async(t,n)=>za(e,t,n),Va(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Ne(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ue(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rs(e,t))},superRefine(e,t){return this.check(is(e,t))},overwrite(e){return this.check(/* @__PURE__ */ Ni(e))},optional(){return Io(this)},exactOptional(){return Ro(this)},nullable(){return Bo(this)},nullish(){return Io(Bo(this))},nonoptional(e){return Ko(this,e)},array(){return M(this)},or(e){return F([this,e])},and(e){return Do(this,e)},transform(e){return Xo(this,Po(e))},default(e){return Ho(this,e)},prefault(e){return Wo(this,e)},catch(e){return Jo(this,e)},pipe(e){return Xo(this,e)},readonly(){return Qo(this)},describe(e){let t=this.clone();return zr.add(t,{description:e}),t},meta(...e){if(e.length===0)return zr.get(this);let t=this.clone();return zr.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return zr.get(e)?.description},configurable:!0}),e)),Ha=/*@__PURE__*/ h(`_ZodString`,(e,t)=>{yn.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Va(e,`_ZodString`,{regex(...e){return this.check(/* @__PURE__ */ Di(...e))},includes(...e){return this.check(/* @__PURE__ */ Ai(...e))},startsWith(...e){return this.check(/* @__PURE__ */ ji(...e))},endsWith(...e){return this.check(/* @__PURE__ */ Mi(...e))},min(...e){return this.check(/* @__PURE__ */ Ti(...e))},max(...e){return this.check(/* @__PURE__ */ wi(...e))},length(...e){return this.check(/* @__PURE__ */ Ei(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Ti(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ Oi(e))},uppercase(e){return this.check(/* @__PURE__ */ ki(e))},trim(){return this.check(/* @__PURE__ */ Fi())},normalize(...e){return this.check(/* @__PURE__ */ Pi(...e))},toLowerCase(){return this.check(/* @__PURE__ */ Ii())},toUpperCase(){return this.check(/* @__PURE__ */ Li())},slugify(){return this.check(/* @__PURE__ */ Ri())}})}),Ua=/*@__PURE__*/ h(`ZodString`,(e,t)=>{yn.init(e,t),Ha.init(e,t),e.email=t=>e.check(/* @__PURE__ */ Vr(Wa,t)),e.url=t=>e.check(/* @__PURE__ */ qr(Ja,t)),e.jwt=t=>e.check(/* @__PURE__ */ ci(uo,t)),e.emoji=t=>e.check(/* @__PURE__ */ Jr(Xa,t)),e.guid=t=>e.check(/* @__PURE__ */ Hr(Ga,t)),e.uuid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.uuidv4=t=>e.check(/* @__PURE__ */ Wr(Ka,t)),e.uuidv6=t=>e.check(/* @__PURE__ */ Gr(Ka,t)),e.uuidv7=t=>e.check(/* @__PURE__ */ Kr(Ka,t)),e.nanoid=t=>e.check(/* @__PURE__ */ Yr(Za,t)),e.guid=t=>e.check(/* @__PURE__ */ Hr(Ga,t)),e.cuid=t=>e.check(/* @__PURE__ */ Xr(Qa,t)),e.cuid2=t=>e.check(/* @__PURE__ */ Zr($a,t)),e.ulid=t=>e.check(/* @__PURE__ */ Qr(eo,t)),e.base64=t=>e.check(/* @__PURE__ */ ai(so,t)),e.base64url=t=>e.check(/* @__PURE__ */ oi(co,t)),e.xid=t=>e.check(/* @__PURE__ */ $r(to,t)),e.ksuid=t=>e.check(/* @__PURE__ */ ei(no,t)),e.ipv4=t=>e.check(/* @__PURE__ */ ti(ro,t)),e.ipv6=t=>e.check(/* @__PURE__ */ ni(io,t)),e.cidrv4=t=>e.check(/* @__PURE__ */ ri(ao,t)),e.cidrv6=t=>e.check(/* @__PURE__ */ ii(oo,t)),e.e164=t=>e.check(/* @__PURE__ */ si(lo,t)),e.datetime=t=>e.check(xa(t)),e.date=t=>e.check(Ca(t)),e.time=t=>e.check(Ta(t)),e.duration=t=>e.check(Da(t))});function O(e){return/* @__PURE__ */ Br(Ua,e)}let k=/*@__PURE__*/ h(`ZodStringFormat`,(e,t)=>{C.init(e,t),Ha.init(e,t)}),Wa=/*@__PURE__*/ h(`ZodEmail`,(e,t)=>{Sn.init(e,t),k.init(e,t)}),Ga=/*@__PURE__*/ h(`ZodGUID`,(e,t)=>{bn.init(e,t),k.init(e,t)}),Ka=/*@__PURE__*/ h(`ZodUUID`,(e,t)=>{xn.init(e,t),k.init(e,t)});function qa(e){return/* @__PURE__ */ Ur(Ka,e)}let Ja=/*@__PURE__*/ h(`ZodURL`,(e,t)=>{Cn.init(e,t),k.init(e,t)});function Ya(e){return/* @__PURE__ */ qr(Ja,e)}let Xa=/*@__PURE__*/ h(`ZodEmoji`,(e,t)=>{wn.init(e,t),k.init(e,t)}),Za=/*@__PURE__*/ h(`ZodNanoID`,(e,t)=>{Tn.init(e,t),k.init(e,t)}),Qa=/*@__PURE__*/ h(`ZodCUID`,(e,t)=>{En.init(e,t),k.init(e,t)}),$a=/*@__PURE__*/ h(`ZodCUID2`,(e,t)=>{Dn.init(e,t),k.init(e,t)}),eo=/*@__PURE__*/ h(`ZodULID`,(e,t)=>{On.init(e,t),k.init(e,t)}),to=/*@__PURE__*/ h(`ZodXID`,(e,t)=>{kn.init(e,t),k.init(e,t)}),no=/*@__PURE__*/ h(`ZodKSUID`,(e,t)=>{An.init(e,t),k.init(e,t)}),ro=/*@__PURE__*/ h(`ZodIPv4`,(e,t)=>{Fn.init(e,t),k.init(e,t)}),io=/*@__PURE__*/ h(`ZodIPv6`,(e,t)=>{In.init(e,t),k.init(e,t)}),ao=/*@__PURE__*/ h(`ZodCIDRv4`,(e,t)=>{Ln.init(e,t),k.init(e,t)}),oo=/*@__PURE__*/ h(`ZodCIDRv6`,(e,t)=>{Rn.init(e,t),k.init(e,t)}),so=/*@__PURE__*/ h(`ZodBase64`,(e,t)=>{Bn.init(e,t),k.init(e,t)}),co=/*@__PURE__*/ h(`ZodBase64URL`,(e,t)=>{Hn.init(e,t),k.init(e,t)}),lo=/*@__PURE__*/ h(`ZodE164`,(e,t)=>{Un.init(e,t),k.init(e,t)}),uo=/*@__PURE__*/ h(`ZodJWT`,(e,t)=>{Gn.init(e,t),k.init(e,t)}),fo=/*@__PURE__*/ h(`ZodNumber`,(e,t)=>{Kn.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r),Va(e,`ZodNumber`,{gt(e,t){return this.check(/* @__PURE__ */ xi(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Si(e,t))},min(e,t){return this.check(/* @__PURE__ */ Si(e,t))},lt(e,t){return this.check(/* @__PURE__ */ yi(e,t))},lte(e,t){return this.check(/* @__PURE__ */ bi(e,t))},max(e,t){return this.check(/* @__PURE__ */ bi(e,t))},int(e){return this.check(mo(e))},safe(e){return this.check(mo(e))},positive(e){return this.check(/* @__PURE__ */ xi(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Si(0,e))},negative(e){return this.check(/* @__PURE__ */ yi(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ bi(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},step(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function A(e){return/* @__PURE__ */ pi(fo,e)}let po=/*@__PURE__*/ h(`ZodNumberFormat`,(e,t)=>{qn.init(e,t),fo.init(e,t)});function mo(e){return/* @__PURE__ */ mi(po,e)}let ho=/*@__PURE__*/ h(`ZodBoolean`,(e,t)=>{Jn.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r)});function j(e){return/* @__PURE__ */ hi(ho,e)}let go=/*@__PURE__*/ h(`ZodNull`,(e,t)=>{Yn.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r)});function _o(e){return/* @__PURE__ */ gi(go,e)}let vo=/*@__PURE__*/ h(`ZodUnknown`,(e,t)=>{Xn.init(e,t),D.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function yo(){return/* @__PURE__ */ _i(vo)}let bo=/*@__PURE__*/ h(`ZodNever`,(e,t)=>{Zn.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(e,t,n,r)});function xo(e){return/* @__PURE__ */ vi(bo,e)}let So=/*@__PURE__*/ h(`ZodArray`,(e,t)=>{$n.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aa(e,t,n,r),e.element=t.element,Va(e,`ZodArray`,{min(e,t){return this.check(/* @__PURE__ */ Ti(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Ti(1,e))},max(e,t){return this.check(/* @__PURE__ */ wi(e,t))},length(e,t){return this.check(/* @__PURE__ */ Ei(e,t))},unwrap(){return this.element}})});function M(e,t){return/* @__PURE__ */ zi(So,e,t)}let Co=/*@__PURE__*/ h(`ZodObject`,(e,t)=>{ir.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),_(e,`shape`,()=>t.shape),Va(e,`ZodObject`,{keyof(){return R(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:yo()})},loose(){return this.clone({...this._zod.def,catchall:yo()})},strict(){return this.clone({...this._zod.def,catchall:xo()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Je(this,e)},safeExtend(e){return Ye(this,e)},merge(e){return Xe(this,e)},pick(e){return Ke(this,e)},omit(e){return qe(this,e)},partial(...e){return Ze(Fo,this,e[0])},required(...e){return Qe(Go,this,e[0])}})});function N(e,t){let n={type:`object`,shape:e??{},...v(t)};return new Co(n)}function P(e,t){return new Co({type:`object`,shape:e,catchall:xo(),...v(t)})}let wo=/*@__PURE__*/ h(`ZodUnion`,(e,t)=>{or.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sa(e,t,n,r),e.options=t.options});function F(e,t){return new wo({type:`union`,options:e,...v(t)})}let To=/*@__PURE__*/ h(`ZodDiscriminatedUnion`,(e,t)=>{wo.init(e,t),sr.init(e,t)});function I(e,t,n){return new To({type:`union`,options:t,discriminator:e,...v(n)})}let Eo=/*@__PURE__*/ h(`ZodIntersection`,(e,t)=>{cr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ca(e,t,n,r)});function Do(e,t){return new Eo({type:`intersection`,left:e,right:t})}let Oo=/*@__PURE__*/ h(`ZodTuple`,(e,t)=>{dr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>la(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function ko(e,t,n){let r=t instanceof S;return new Oo({type:`tuple`,items:e,rest:r?t:null,...v(r?n:t)})}let Ao=/*@__PURE__*/ h(`ZodRecord`,(e,t)=>{hr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ua(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function L(e,t,n){return!t||!t._zod?new Ao({type:`record`,keyType:O(),valueType:e,...v(t)}):new Ao({type:`record`,keyType:e,valueType:t,...v(n)})}let jo=/*@__PURE__*/ h(`ZodEnum`,(e,t)=>{gr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})}});function R(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new jo({type:`enum`,entries:n,...v(t)})}let Mo=/*@__PURE__*/ h(`ZodLiteral`,(e,t)=>{_r.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>na(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function z(e,t){return new Mo({type:`literal`,values:Array.isArray(e)?e:[e],...v(t)})}let No=/*@__PURE__*/ h(`ZodTransform`,(e,t)=>{vr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ia(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(rt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(rt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Po(e){return new No({type:`transform`,transform:e})}let Fo=/*@__PURE__*/ h(`ZodOptional`,(e,t)=>{br.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>va(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Fo({type:`optional`,innerType:e})}let Lo=/*@__PURE__*/ h(`ZodExactOptional`,(e,t)=>{xr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>va(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ro(e){return new Lo({type:`optional`,innerType:e})}let zo=/*@__PURE__*/ h(`ZodNullable`,(e,t)=>{Sr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>da(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bo(e){return new zo({type:`nullable`,innerType:e})}let Vo=/*@__PURE__*/ h(`ZodDefault`,(e,t)=>{Cr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ho(e,t){return new Vo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Uo=/*@__PURE__*/ h(`ZodPrefault`,(e,t)=>{Tr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ma(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wo(e,t){return new Uo({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Go=/*@__PURE__*/ h(`ZodNonOptional`,(e,t)=>{Er.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ko(e,t){return new Go({type:`nonoptional`,innerType:e,...v(t)})}let qo=/*@__PURE__*/ h(`ZodCatch`,(e,t)=>{Or.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ha(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jo(e,t){return new qo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let Yo=/*@__PURE__*/ h(`ZodPipe`,(e,t)=>{kr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ga(e,t,n,r),e.in=t.in,e.out=t.out});function Xo(e,t){return new Yo({type:`pipe`,in:e,out:t})}let Zo=/*@__PURE__*/ h(`ZodReadonly`,(e,t)=>{jr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qo(e){return new Zo({type:`readonly`,innerType:e})}let $o=/*@__PURE__*/ h(`ZodLazy`,(e,t)=>{Nr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function es(e){return new $o({type:`lazy`,getter:e})}let ts=/*@__PURE__*/ h(`ZodCustom`,(e,t)=>{Pr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ra(e,t,n,r)});function ns(e,t){return/* @__PURE__ */ Bi(ts,e??(()=>!0),t)}function rs(e,t={}){return/* @__PURE__ */ Vi(ts,e,t)}function is(e,t){return/* @__PURE__ */ Hi(e,t)}let as=O().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),B=as.brand(),V=as.brand(),os=as.brand();as.brand(),as.brand();let ss=O().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),cs=ss.pipe(B),ls=cs.refine(e=>e!==`codex`,`The official Codex identity is reserved`),us=O().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`),ds=Ya().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),fs=N({en:O().max(4096),"zh-CN":O().max(4096).optional()}).strict(),ps=N({commands:M(N({terminal:O().max(256),command:O().max(4096)}).strict()).max(8),before:fs.optional(),after:fs.optional(),downloads:M(N({label:O().max(128),url:ds}).strict()).max(8).optional()}).strict(),ms={id:cs,name:O().trim().min(1).max(128),version:O().min(1).max(128),kind:z(`usage`).optional(),iconStyle:N({vector:N({viewBox:O().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:O().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:M(N({d:O().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:R([`evenodd`,`nonzero`]).optional(),fill:O().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:O().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:A().min(0).max(50).optional(),paddingRatio:A().min(0).max(.25).optional()}).strict().optional(),installation:ps.optional(),notice:fs.optional(),launchCommand:z(!0).optional(),links:N({website:ds.optional(),documentation:ds.optional(),installation:ds.optional()}).strict().optional()};N({manifestVersion:z(1),...ms,adapterApiVersion:A().int().positive(),entry:us,icon:us.optional()}).strict();let hs=O().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),gs=N({...ms,icon:hs.optional()}).strict();N({}).strict(),N({plugins:M(gs.extend({id:ls})).max(128)}).strict(),N({version:z(1),enabled:M(cs).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});function _s(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 vs=F([O(),A(),j(),_o()]);function ys(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 bs=ns(ys,{message:`JSON value must not contain circular references`}),xs=es(()=>F([vs,M(xs),L(O(),xs)])),H=bs.pipe(xs);bs.pipe(M(xs));let Ss=bs.pipe(L(O(),xs)),U=ss,Cs=R([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),ws=R([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),Ts=O().trim().min(1).max(128);function Es(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}}function Ds(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`gif`:return`image/gif`;case`svg`:return`image/svg+xml`;case`woff2`:return`font/woff2`;case`json`:return`application/json`;case`css`:return`text/css`;default:return Es(e)}}let Os=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),ks=us.refine(e=>Os(e)&&Ds(e)!==void 0,`Expected a relative Desktop extension asset path with a supported suffix`),As=us.refine(e=>Es(e)!==void 0&&Os(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),js=O().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Ya({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 Ms(e){return P({en:e,"zh-CN":e})}let Ns=Ms(O().trim().min(1)),Ps=M(ws).max(ws.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),Fs=M(Cs).max(Cs.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),Is={key:O().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:Ns,description:Ns.optional()},Ls={...Is,step:A().positive().optional(),default:A().optional()},Rs=P({value:O(),label:Ns}),zs=I(`type`,[P({...Is,type:z(`boolean`),default:j().optional()}),P({...Is,type:z(`string`),placeholder:Ns.optional(),default:O().optional()}),P({...Ls,type:z(`number`),min:A().optional(),max:A().optional()}),P({...Ls,type:z(`range`),min:A(),max:A()}),P({...Is,type:z(`select`),options:M(Rs).min(1),default:O().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`)}}),Bs=N({manifestVersion:mo().positive(),id:U,name:F([Ts,Ms(Ts)]),version:O().min(1).max(128),desktopApi:mo().positive()}).passthrough().extend({manifestVersion:z(1),desktopApi:z(1),description:P({en:O().max(4096),"zh-CN":O().max(4096).optional()}).optional(),author:O().trim().min(1).max(128).optional(),repository:js.optional(),details:P({en:O().max(16384),"zh-CN":O().max(16384).optional()}).optional(),icon:As.optional(),screenshots:M(As).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:P({script:us,style:us.optional()}).optional(),backend:P({script:us.refine(Os)}).optional(),slots:Fs.default(()=>[]),settingsSchema:M(zs).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:Ps.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),Vs=P({version:z(1),revision:mo().nonnegative(),enabled:M(U).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`),reloadToken:qa().optional()}),Hs=O().regex(/^[a-f0-9]{64}$/u),Us=P({state:R([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:Hs.optional(),error:O().optional(),conflictWith:U.optional()});P({controllerPid:mo().positive(),targetId:O().nullable(),updatedAt:xa(),handledReloadToken:qa().optional(),extensions:L(O(),Us)});let Ws=R([`official`,`community`]);function Gs(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Ks=js.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||Gs(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`),qs=P({id:U,version:O().trim().min(1).max(128),name:Ns.extend({en:Ts,"zh-CN":Ts}),description:Ms(O().trim().min(1).max(4096)),details:Ms(O().trim().min(1).max(16384)).optional(),author:O().trim().min(1).max(128),repository:js,stars:A().int().min(0).optional(),downloads:A().int().min(0).optional(),categories:Ps.optional(),trustTier:Ws.default(`community`),icon:js.optional(),screenshots:M(js).max(4).optional(),downloadUrl:Ks,sha256:Hs,slots:Fs.optional(),publishedAt:O().optional(),updatedAt:O().optional(),minCodexHostVersion:O().optional()}),Js=P({schemaVersion:z(1),generatedAt:O(),extensions:M(qs).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}),Ys={id:U};P({...Ys,path:ks}),P({mimeType:O(),dataUrl:O()}),P(Ys),P({...Ys,values:Ss}),P({values:Ss});let Xs=O().trim().min(1).max(128);P({...Ys,method:Xs,params:H.optional()}),P({result:H});let Zs=[`codexhost/desktop/extensions/list`,`codexhost/desktop/extensions/enable`,`codexhost/desktop/extensions/disable`,`codexhost/desktop/extensions/disable-all-and-reload`,`codexhost/desktop/extensions/catalog`,`codexhost/desktop/extensions/install`,`codexhost/desktop/extensions/uninstall`,`codexhost/desktop/extensions/asset`,`codexhost/desktop/extensions/settings/get`,`codexhost/desktop/extensions/settings/set`,`codexhost/desktop/extensions/backend/invoke`],Qs=mo().nonnegative();P({}),P({id:U,expectedRevision:Qs}),P({expectedRevision:Qs.optional()});let $s=e=>O().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),ec=P({id:O().min(1),manifest:Bs.optional(),iconDataUrl:$s(131072).optional(),screenshotDataUrls:M($s(524288)).max(4).optional(),enabled:j(),status:Us}),tc=P({configuration:Vs,desktopConnected:j(),diagnostics:M(O()),extensions:M(ec)});P({forceRefresh:j().optional()}),P({catalogUrl:O(),source:R([`remote`,`fallback`]),fetchedAt:O(),cached:j(),extensions:Js.shape.extensions,error:O().optional()}),P({source:I(`type`,[P({type:z(`catalog`),id:U}),P({type:z(`url`),url:js,expectedSha256:Hs.optional()}),P({type:z(`zip-base64`),fileName:O().trim().min(1).max(255),contentBase64:O().min(4).max(89478488).refine(e=>e.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/u.test(e),`Expected standard padded base64`)})])}),P({extensionId:U,version:O().min(1),replaced:j(),installedPath:O(),list:tc}),P({id:U}),P({removedId:U,list:tc}),I(`state`,[P({state:z(`saved`),configuration:Vs}),P({state:z(`slot-conflict`),conflictWith:U}),P({state:z(`revision-conflict`),revision:Qs})]);let nc=P({code:O().min(1),message:O().min(1),retryable:j(),diagnostic:O().min(1).optional(),stage:O().min(1).optional(),durationMs:A().int().nonnegative().optional(),stderrTail:O().min(1).optional()}).superRefine(_s([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),rc=O().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),ic=e=>O().min(1).max(e).refine(e=>e.trim().length>0),ac=L(rc,N({label:ic(256).optional(),description:ic(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),oc=L(rc,ic(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),sc=O().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),W=sc.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),cc=N({modes:M(N({id:W,label:sc.max(256),description:sc.max(1024).optional(),dangerous:j().optional(),localizations:ac.optional()}).strict()).min(1).max(32),defaultModeId:W}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});N({threadId:V,permissionModeId:W}).strict();let G=A().int().safe().nonnegative(),lc=A().finite().nonnegative(),uc=A().finite().min(0).max(100),dc=N({version:F([z(3),z(4)]).optional(),requestId:O().min(1),turnId:O().min(1).max(1024),outputTokens:G,startedAtMs:G,completedAtMs:G}).strict().refine(e=>e.completedAtMs>e.startedAtMs),fc=N({version:F([z(2),z(3),z(4)]).optional(),value:lc,turnId:O().min(1).max(1024),at:G}).strict();N({outputTimings:M(dc).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:fc.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:fc.extend({value:G}).optional()}).strict();let pc=e=>oc.refine(t=>Object.values(t).every(t=>t.length<=e)),mc=N({composerIndicators:M(N({kind:z(`countdown`),id:O().min(1).max(64),expiresAtUnix:G,label:pc(256).optional(),tooltip:pc(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:G.optional(),cachedInputTokens:G.optional(),cacheWriteInputTokens:G.optional(),outputTokens:G.optional(),outputTokensPerSecond:lc.optional(),sessionOutputTokensPerSecond:lc.optional(),apiOutputTokensPerSecond:lc.optional(),reasoningOutputTokens:G.optional(),totalTokens:G.optional(),totalCostUsd:lc.optional(),totalCredits:lc.optional(),contextUsagePercent:lc.optional(),cacheHitRatePercent:uc.optional(),contextWindowTokens:G.optional(),contextUsedTokens:G.optional(),planFiveHourUsedPercent:uc.optional(),planFiveHourResetsAtUnix:G.optional(),planSevenDayUsedPercent:uc.optional(),planSevenDayResetsAtUnix:G.optional(),sessionCacheHitRatePercent:uc.optional(),timeToFirstOutputMs:G.optional(),costSource:R([`publicPrice`,`native`]).optional(),unpricedModels:M(O().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`]})}),hc=A().finite().min(0).max(100),gc=R([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),_c=N({id:O().min(1).max(256),label:O().min(1).max(256),localizations:ac.optional()}).strict(),vc=N({product:O().min(1),periodType:gc.optional(),scope:_c.optional(),localizations:ac.optional(),used:A().finite().nonnegative().optional(),limit:A().finite().nonnegative().optional(),unit:O().min(1).max(32).optional(),usagePercent:hc,resetsAt:O().min(1).optional()}).strict(),yc=N({availableCount:A().int().safe().positive(),nextExpiresAt:O().min(1).optional(),expiresAt:M(O().min(1)).min(1).max(32).optional()}).strict(),bc=N({used:A().finite().nonnegative().optional(),limit:A().finite().nonnegative().optional(),unit:O().min(1).max(32).optional(),label:O().min(1).optional(),scope:_c.optional(),localizations:ac.optional(),usedPercent:hc,resetsAt:O().min(1).optional(),periodType:gc,productUsage:M(vc).min(1).optional(),resetCredits:yc.optional()}).strict(),xc=N({amount:A().finite().nonnegative(),currency:O().trim().min(1).max(8),label:O().trim().min(1).max(128).optional()}).strict();N({threadId:V,refresh:z(`exact`).optional()}).strict(),N({threadId:V,usage:mc.nullable(),accountCredits:bc.optional(),accountBalance:xc.optional(),accountCreditsSupported:j().optional()}).strict();let Sc=O().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),K=N({id:Sc.max(512).regex(/^[A-Za-z0-9._~-]+$/u,`Model Ref must use transport-safe opaque characters`).brand()}).strict(),q=Sc.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Cc=Sc.max(256),wc=N({id:q,label:Sc.max(256)}).strict(),Tc=N({ref:K,label:Sc.max(256),resolvedModelLabel:Cc.optional(),fastModel:K.optional(),supportedThinkingOptionIds:M(q).optional()}).strict(),Ec=M(wc).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)}),Dc=N({models:M(Tc),defaultModel:K.optional(),thinkingOptions:Ec,defaultThinkingOptionId:q.optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set,r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.has(a.ref.id)&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.add(a.ref.id),a.fastModel&&((n.has(a.fastModel.id)||e.models.some(e=>e.ref.id===a.fastModel?.id))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.add(a.fastModel.id));let o=/* @__PURE__ */ new Set;for(let[e,n]of(a.supportedThinkingOptionIds??[]).entries())o.has(n)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,e]}),o.add(n),r.has(n)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,e]})}e.defaultModel&&!n.has(e.defaultModel.id)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),Oc=N({fork:j(),forkAcrossCwd:j(),rollbackLastTurn:j()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),kc=R([`live`,`atCreate`]),Ac=N({configuration:N({selectModel:j(),selectThinkingOption:j(),selectPermissionMode:j(),permissionModeScope:kc.default(`live`)}).strict(),history:Oc,subagents:N({observe:j(),readTranscript:j()}).strict().optional(),autonomousTurns:N({observe:j()}).strict().optional(),steer:j().optional()}).strict();N({effectiveModel:K.optional(),resolvedModelLabel:Cc.optional(),effectiveThinkingOptionId:q.optional(),availableThinkingOptions:Ec.optional(),effectivePermissionModeId:W.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 jc=N({open:z(!0)}).strict();F([N({status:z(`ready`),catalog:Dc,permissionModes:cc.optional(),capabilities:Ac,webUi:jc.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),N({status:R([`notInstalled`,`unavailable`,`error`]),error:nc}).strict()]),N({harnessId:B,cwd:Sc.max(16384).optional(),refresh:j().optional(),purpose:z(`availability`).optional()}).strict(),N({harnessId:B}).strict(),N({}).strict(),N({threadId:V,model:K}).strict(),N({threadId:V,thinkingOptionId:q}).strict(),N({threadId:V,includeReferenceCapability:j().optional()}).strict(),I(`owner`,[N({owner:z(`codex`),locked:j(),effectiveModel:K.optional(),resolvedModelLabel:Cc.optional(),effectiveThinkingOptionId:q.optional(),effectivePermissionModeId:W.optional(),history:Oc.optional(),supportsThreadReferences:z(!0).optional()}).strict(),N({owner:z(`external`),harnessId:Sc.max(256),transportModelId:Sc.max(1024),effectiveModel:K.optional(),resolvedModelLabel:Cc.optional(),effectiveThinkingOptionId:q.optional(),availableThinkingOptions:Ec.optional(),effectivePermissionModeId:W.optional(),history:Oc,usage:mc.optional(),locked:z(!0)}).strict()]),N({threadIds:M(V).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 Mc=I(`owner`,[N({threadId:V,owner:z(`codex`)}).strict(),N({threadId:V,owner:z(`external`),harnessId:O().max(256).pipe(B)}).strict()]);N({threads:M(Mc).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),N({threadId:V,text:O().optional()}).strict(),N({kind:z(`application`),value:O().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),xe}}).pipe(N({expectedTurnId:os,clientUserMessageId:O().min(1),delivery:R([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),R([`activeTurn`,`newTurn`]),N({delivery:R([`official`,`activeTurn`,`newTurn`])}).strict(),N({threadId:V}).strict(),N({confirmed:j()}).strict(),[...Zs],N({threadIds:M(O().min(1))}).strict(),N({threadId:O().min(1).max(1024),pinned:j()}).strict(),N({}).strict(),N({parents:L(O().min(1),O().min(1))}).strict(),N({prompt:O().max(16384).optional()}).strict(),N({projects:M(N({id:O(),name:O(),rootPaths:M(O())})),assignments:L(O(),O()),projectless:M(O()),pinned:M(O())});let Nc=L(O(),yo()),Pc=N({epoch:O().uuid(),sequence:A().int().nonnegative()});I(`type`,[N({type:z(`skills-changed`),cursor:Pc,cwd:O().optional()}),N({type:z(`harness-inspection-changed`),cursor:Pc,harnessId:O().min(1)}),N({type:z(`display-settings-changed`),cursor:Pc}),N({type:z(`preferences-changed`),cursor:Pc,revision:A().int().nonnegative()}),N({type:z(`hello`),version:z(1),cursor:Pc,reset:j()}),N({type:z(`changed`),cursor:Pc,threadId:O().min(1),method:O().min(1)})]);let Fc=I(`type`,[N({type:z(`text`),id:O(),prompt:O(),secret:j().optional(),optional:j().optional()}),N({type:z(`choice`),id:O(),prompt:O(),multiple:j(),allowOther:j(),optional:j().optional(),options:M(N({value:O(),label:O(),description:O().optional()}))})]),Ic=I(`type`,[N({type:z(`approval`),title:O(),description:O().optional(),subject:yo().optional(),actions:M(N({id:O(),label:O(),effect:O()}))}),N({type:z(`question`),title:O().optional(),questions:M(Fc)})]),Lc=N({requestId:F([O(),A().int()]),threadId:O(),kind:R([`approval`,`question`]),interaction:Ic,request:Nc}),Rc=N({id:O().min(1),clientUserMessageId:O().min(1),input:M(Nc),presentationInput:M(Nc).nullable().optional()}).passthrough();N({fields:M(N({path:M(F([O(),A().int().nonnegative()])),originalLength:A().int().nonnegative()}))});let zc=N({id:O().min(1),status:O().min(1),codexhostTurnOutcome:N({status:z(`unknown`),reason:O()}).optional(),items:M(N({id:O().min(1),type:O().min(1)}).passthrough()),codexhostFileOperations:M(N({beforeItemId:O().nullable(),item:N({id:O().min(1),type:O().min(1)}).passthrough()})).optional(),error:N({message:O().optional()}).passthrough().nullable().optional(),fingerprint:O().min(1).optional(),unchanged:z(!0).optional()}).passthrough(),Bc=N({id:O().min(1).max(512),fingerprint:O().min(1).max(128)});N({threadId:O().min(1),knownTurns:M(Bc).max(64).optional(),truncateToolOutput:j().optional()});let Vc=N({harnessId:O().min(1),nativeSessionId:O().min(1)});N({cursor:Pc,activeTurnId:O().min(1).nullable().optional(),command:N({name:O().min(1),turn:zc,subsequentTurnId:O().min(1).optional()}).optional(),thread:N({id:O().min(1),cwd:O(),modelProvider:O().min(1),createdAt:A(),updatedAt:A(),status:N({type:O()}).passthrough(),name:O().nullable().optional(),preview:O().optional(),codexhostImportSource:Vc.optional(),turns:M(zc).length(0)}).passthrough(),turnsPage:N({data:M(zc).max(5),nextCursor:O().nullable()}),configuration:N({native:N({model:O().min(1).max(1024).optional(),reasoningEffort:O().min(1).max(128).optional()}).optional(),effectiveModel:K.optional(),effectiveThinkingOptionId:q.optional(),effectivePermissionModeId:W.optional()}),queue:N({items:M(Rc),pausedReason:R([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:M(Lc)}),N({version:z(1),owner:z(`service`).optional(),pid:A().int().positive(),port:A().int().min(1).max(65535),token:O().regex(/^[0-9a-f]{64}$/u),startedAt:A(),epoch:O().uuid()}),N({epoch:O().uuid(),threadId:O().min(1),requestId:F([O(),A().int()]),result:Nc}),N({includeArchived:j().optional(),officialCursor:N({live:O().nullable(),archived:O().nullable().optional()}).strict().optional()}).strict(),N({threads:M(Ss),ownership:M(Mc),archivedThreadIds:M(V),officialCursor:N({live:O().nullable(),archived:O().nullable().optional()}).strict().optional()}).strict();let Hc=R([`running`,`waiting`,`idle`,`unknown`]),Uc=P({harnessId:B,title:O().optional(),status:Hc,archived:j()}),Wc=P({revision:mo().nonnegative(),parents:L(V,V),nodes:L(V,Uc),truncated:j()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,nodes:t})=>Object.entries(e).every(([e,n])=>Object.hasOwn(t,e)&&Object.hasOwn(t,n)),`Missing Thread tree node`),Gc=O().min(1).max(128);P({});let Kc=P({subscriptionId:Gc});P({}),Kc.extend({snapshot:Wc});let qc=O().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);N({available:j()}).strict(),N({path:O().min(1),mimeType:qc}).strict();let Jc=R([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);I(`ok`,[N({ok:z(!0),text:O()}).strict(),N({ok:z(!1),error:N({code:Jc}).strict()}).strict()]),N({threadId:V.optional(),cwd:O().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Yc=N({name:O().min(1).regex(/^[^\s[\]]+$/u),description:O().optional(),path:O().min(1),scope:R([`project`,`global`]),source:O().min(1)}).strict();N({revision:A().int().nonnegative(),complete:j(),skills:M(Yc),warnings:M(O()).optional()}).strict(),N({cwd:O().min(1).optional()}).strict();let Xc=N({kind:R([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:O().min(1)}).strict(),Zc=I(`status`,[N({status:z(`not-installed`)}),N({status:z(`not-running`)}),N({status:z(`not-logged-in`)}),N({status:z(`https-disabled`)}),N({status:z(`not-serving`),command:O()}),N({status:z(`occupied`),target:O()}),N({status:z(`serving`),url:O(),funnel:j()}),N({status:z(`error`),message:O()})]);N({state:Zc,error:O().optional()}).strict();let Qc=I(`status`,[N({status:z(`on`)}),N({status:z(`off`)}),N({status:z(`invalid`),reason:O()})]),$c=N({lan:j(),autostart:Qc}).strict(),el=N({expiresAt:O().optional(),issuing:j(),failure:N({detail:O().optional(),retryAt:O(),paused:j()}).optional()}),tl=I(`status`,[N({status:z(`off`),reason:R([`invite`,`name-taken`,`banned`]).optional()}),N({status:z(`connecting`),reason:R([`full`,`unreachable`]).optional()}),N({status:z(`connected`),url:O(),certificate:el}),N({status:z(`missing-certificate`),url:O(),certificate:el}),N({status:z(`stopped`),reason:R([`replaced`,`rejected`,`unsupported-version`])})]);O().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()),O().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let nl=R([`official`,`self-hosted`]);N({secret:O().min(1),lastUsedAt:A().nullable(),networkUrls:M(Xc),directCandidates:M(Xc).optional(),tailscale:Zc,background:$c.optional(),relay:N({state:tl,enabled:j(),kind:nl,officialHost:O(),customHost:O().optional(),officialHostname:O().optional(),customHostname:O().optional(),quotaUntil:O().optional()}).strict().optional()}).strict();let rl=P({threadId:O().min(1).max(1024),view:R([`result`,`messages`]),from:A().int().min(1).max(2**53-1).optional(),to:A().int().min(1).max(2**53-1).optional()}),il=N({id:O().min(1).max(256),harnessId:O().min(1),label:O().min(1).max(512),provider:R([`openai-codex`,`xai`])}).strict(),al=O().regex(/^[a-z][a-z0-9-]{0,47}$/),ol=N({name:al,source:il,importedAt:O()}).strict(),sl=I(`action`,[N({action:z(`list`)}).strict(),N({action:z(`import`),sourceId:O().min(1).max(256),name:al,confirmed:z(!0)}).strict(),N({action:z(`reimport`),sourceId:O().min(1).max(256),name:al,confirmed:z(!0)}).strict(),N({action:z(`remove`),name:al,confirmed:z(!0)}).strict()]),cl=N({provider:O().min(1).max(128),type:R([`oauth`,`api_key`,`unknown`]),label:O().min(1).max(512).optional(),vendor:R([`openai-codex`,`xai`]).optional()}).strict();N({sources:M(il),targets:M(N({harnessId:O(),providers:M(R([`openai-codex`,`xai`])),imports:M(ol),others:M(cl).default([])}).strict())}).strict(),N({targetHarnessId:O().min(1).max(128).optional(),request:sl}).strict(),N({events:j()});let ll=M(P({agent:O().min(1).max(128),section:R([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);P({entries:ll.nullable()}),P({}),P({entries:ll,initializeOnly:j().optional()});let ul=P({enabled:j(),timeoutMinutes:A().int().min(5).max(1440)});Object.freeze({enabled:!1,timeoutMinutes:10});let dl=O().regex(/^external$/u),fl=B.transform(e=>String(e)),pl=P({model:K.optional(),thinkingOptionId:q.optional(),permissionModeId:W.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),ml=P({lastHarness:B.optional(),byHarness:L(fl,pl)}),hl=O().min(1).max(1024),gl=P({idleRelease:ul.optional(),favorites:L(fl,M(hl).max(2048)).default({}),newThread:ml.optional()});P({scope:dl,revision:A().int().nonnegative(),values:gl}),P({scope:dl.default(`external`)});let _l=I(`kind`,[P({kind:z(`idleRelease`),value:ul}),P({kind:z(`favorite`),harnessId:B,modelId:hl,enabled:j()}),P({kind:z(`favorites`),harnessId:B,modelIds:M(hl).max(2048)}),P({kind:z(`newThread`),lastHarness:B.optional(),harnessId:B.optional(),configuration:pl.optional()})]);P({scope:dl.default(`external`),operations:M(_l).min(1).max(256),initializeOnly:j().optional(),expectedRevision:A().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),P({version:z(1),revision:A().int().nonnegative(),scopes:L(dl,gl)});let vl=A().finite().nonnegative(),yl=P({input:vl,output:vl,cacheRead:vl.optional(),cacheWrite:vl.optional(),cacheWrite1h:vl.optional()}),bl=O().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);P({path:O(),entries:M(P({key:O(),price:yl})),error:O().nullable()}),P({}),P({key:bl,price:yl.nullable(),previousKey:bl.optional()}),P({model:bl});let xl=P({official:j().optional(),canonicalModelId:O().min(1).optional(),provider:O().min(1).max(512),model:O().min(1).max(512),price:yl});P({price:yl.nullable(),suggestions:M(xl).max(6).optional()});let Sl=[`today`,`7d`,`30d`,`90d`,`all`],J=A().int().min(0).max(2**53-1),Cl=O().regex(/^\d{4}-\d{2}-\d{2}$/u),Y=O().min(1).max(128),X=O().min(1).max(512),wl=O().min(1).max(4096);P({range:R(Sl),timeZone:O().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:Y.optional(),model:X.nullable().optional(),project:wl.nullable().optional(),date:Cl.optional()});let Tl=P({requests:J,inputTokens:J,cachedInputTokens:J,cacheWriteInputTokens:J,cacheKnownInputTokens:J,cacheHitCachedInputTokens:J,cacheHitInputTokens:J,outputTokens:J,reasoningOutputTokens:J,costUsd:A().finite().min(0),unpricedRequests:J,unmeteredRequests:J}),El=Tl.shape,Dl=P({harness:Y,sessionId:O().min(1).max(512),project:wl.nullable(),title:O().min(1).max(200).optional(),models:M(X).max(16),firstAtMs:J,lastAtMs:J,...El});P({range:R(Sl),from:Cl.nullable(),to:Cl,filters:P({harness:Y.nullable(),model:X.nullable(),unknownModel:j(),project:wl.nullable(),unknownProject:j(),date:Cl.nullable()}),reading:P({complete:j(),sources:J,read:J}),failures:M(P({harness:Y,message:O().max(2048)})).max(256),options:P({harnesses:M(Y).max(256),models:M(X.nullable()).max(4096),projects:M(wl.nullable()).max(4096)}),modelLabels:M(P({harness:Y,model:X,label:X})).max(4096).optional(),credits:M(P({harness:Y,model:X.nullable(),credits:A().finite().min(0),reportedRequests:J,requests:J})).max(4096).optional(),totals:Tl,daily:M(P({date:Cl,harness:Y,...El})).max(2e5),hourly:M(P({weekday:A().int().min(0).max(6),hour:A().int().min(0).max(23),...El})).max(168),byHarness:M(P({harness:Y,...El})).max(256),byModel:M(P({model:X.nullable(),...El,harnessPricedRequests:J})).max(4096),byProject:M(P({project:wl.nullable(),...El})).max(4096),sessions:M(Dl).max(100),recentSessions:M(Dl).max(100).optional()}),N({threadId:V}),N({discarded:j()});let Ol=I(`type`,[N({id:O().min(1),type:z(`choice`),prompt:O(),options:M(N({value:O().min(1),label:O(),description:O().optional()})).min(1),multiple:j(),allowOther:j(),optional:j()}),N({id:O().min(1),type:z(`text`),prompt:O(),multiline:j(),secret:z(!1),optional:j(),placeholder:O().optional(),prefill:O().optional()})]),kl=N({interactionId:O().min(1),turnId:O().min(1),title:O().optional(),questions:M(Ol).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});P({threadId:O().min(1)}),N({questions:M(kl)}),P({threadId:O().min(1),turnId:O().min(1),interactionId:O().min(1),answers:L(O(),M(O())),cancelled:j().default(!1)}),N({accepted:z(!0)});let Al=/* @__PURE__ */ new Set([`codexhostTurnChanges`,`codexhostToolOutput`]),jl=N({path:O(),oldText:O().nullable(),newText:O()});N({sessionId:O().min(1),turn:A().int().nonnegative(),path:O().min(1).optional()}),N({diffs:M(jl)}),P({}),P({}),N({reference:N({sessionId:O().min(1),epoch:O().min(1),turn:A().int().nonnegative(),seq:A().int().nonnegative(),callId:O().min(1),part:A().int().nonnegative(),version:O().min(1)}),length:A().int().nonnegative(),bytes:A().int().nonnegative()}),P({title:O().trim().min(1).max(200),type:R([`info`,`warning`,`danger`]),body:O().trim().min(1).max(16384)}),P({}),P({url:O().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 Ml=R([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),Nl=R([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);P({threadId:O(),title:O(),harnessId:O(),state:Ml,reason:Nl,inactiveMs:A().nonnegative()}),P({threadId:V,turnId:os});let Pl=N({email:O().trim().min(1).max(320).optional(),label:O().trim().min(1).max(256).optional(),plan:O().trim().min(1).max(128).optional(),credits:bc.optional(),balance:xc.optional()}).strict();function Fl(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 Il=Fl(Pl),Ll={harnessId:B,harnessName:O().trim().min(1).max(128)},Rl=N(Ll).strict();N({}).strict(),N({sources:M(Rl).max(128)}).strict(),N({harnessId:B,refresh:j().optional()}).strict(),N({...Ll,account:Il.nullable(),accounts:M(Il).max(8).optional()}).strict(),N({refresh:j().optional()}).strict(),N({accounts:M(Fl(Pl.extend(Ll))).max(128)}).strict(),N({harnessId:ls,model:K.optional(),thinkingOptionId:q.optional(),permissionModeId:W.optional(),prewarm:z(!0).optional()}).strict();let zl=O().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);N({harnessId:ls}).strict().extend({path:zl.nullable()}),N({path:zl.nullable(),restartRequired:j()}).strict(),N({harnessId:B,action:R([`check`,`update`,`install`])}).strict();let Bl=N({currentVersion:O().min(1).max(128),latestVersion:O().min(1).max(128),updateAvailable:j(),canUpdate:j(),versionKind:R([`cli`,`application`]).optional(),manualUpdateUrl:Ya().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:O().max(2048).optional(),messageCode:O().min(1).max(128).optional(),notice:oc.optional(),latestVersionKind:R([`unknown`,`tracking-branch`]).optional()}).strict();N({taskId:O().uuid()}).strict(),I(`status`,[N({taskId:O().uuid(),status:z(`running`)}).strict(),N({taskId:O().uuid(),status:z(`succeeded`),result:Bl}).strict(),N({taskId:O().uuid(),status:z(`failed`),error:N({code:A().int(),message:O().min(1).max(2048)}).strict()}).strict()]);let Vl=O().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Hl=O().trim().min(1),Ul=R([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),Wl=N({accountId:Vl,label:Hl.max(256),email:O().email().max(320).optional(),planType:Ul.optional()}).strict(),Gl=R([`ready`,`unavailable`]);N({version:z(2),currentAccountId:Vl.nullable(),phase:Gl,revision:A().int().nonnegative(),instanceId:Hl.max(1024).optional(),accounts:M(Wl).max(1)}).strict(),N({accountId:Vl,refresh:j().optional()}).strict(),N({accountId:Vl,usage:mc.nullable(),accountCredits:bc.optional(),freshness:R([`live`,`cached`]),observedAt:O().datetime().nullable()}).strict();let Kl=1e3,ql=O().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Jl=ql.max(1024),Yl=N({nativeSessionId:Jl,title:ql.max(4096).nullable(),updatedAt:A().int().nonnegative().max(864e13),cwd:ql.max(16384),running:j().nullable()}).strict();N({}).strict(),N({harnesses:M(N({harnessId:ls,name:ql.max(128)}).strict()).max(128)}).strict(),N({harnessId:ls,query:O().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:A().int().nonnegative().safe().optional(),limit:A().int().min(1).max(Kl).optional()}).strict(),N({candidates:M(Yl).max(Kl),total:A().int().nonnegative().safe()}).strict(),N({harnessId:ls,nativeSessionId:Jl}).strict(),N({threadId:ql.max(1024).pipe(V)}).strict();let Xl=O().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Zl=Jl,Ql=Yl;N({}).strict(),N({candidates:M(Ql).max(1e3)}).strict(),N({nativeSessionId:Zl}).strict(),N({threadId:Xl.max(1024).pipe(V)}).strict(),N({threadId:V,lastTurnId:os}).strict(),N({threadId:V}).strict();let $l=O().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();N({commands:M(N({id:$l,invocation:O().min(1).max(128),label:O().trim().min(1).max(128),description:O().trim().min(1).max(512).optional(),localizations:ac.optional(),argumentMode:R([`none`,`text`]),kind:R([`command`,`skill`]).optional()}).strict()),warnings:M(O().min(1)).optional(),source:R([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),N({harnessId:B,cwd:O().min(1).optional()}).strict(),N({threadId:V}).strict(),N({threadId:V,commandId:$l,turnId:os.optional(),arguments:Ss.optional()}).strict(),N({accepted:z(!0),turnId:os.optional()}).strict();let eu=z(`2.0`).optional(),Z=xo().optional(),tu=O().min(1),nu=F([O(),A().int()]),ru=N({code:A().int(),message:O(),data:H.optional()}).catchall(H).superRefine(_s([`data`]));F([N({jsonrpc:eu,id:nu,method:tu,params:H.optional(),result:Z,error:Z}).catchall(H).superRefine(_s([`jsonrpc`,`params`,`result`,`error`])),N({jsonrpc:eu,id:Z,method:tu,params:H.optional(),result:Z,error:Z}).catchall(H).superRefine(_s([`jsonrpc`,`id`,`params`,`result`,`error`])),N({jsonrpc:eu,id:nu,method:Z,params:Z,result:H,error:Z}).catchall(H).superRefine(_s([`jsonrpc`,`method`,`params`,`error`])),N({jsonrpc:eu,id:nu,method:Z,params:Z,result:Z,error:ru}).catchall(H).superRefine(_s([`jsonrpc`,`method`,`params`,`result`]))]);let iu=O().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});P({harnessId:B,nativeSessionId:iu,locator:H.optional(),formatVersion:z(1)}).superRefine(_s([`locator`])),P({harnessId:B,nativeSessionId:iu,nativeTurnKey:iu,formatVersion:z(1)}),P({harnessId:B,nativeSessionId:iu,checkpointId:iu,locator:H.optional(),formatVersion:z(1)}).superRefine(_s([`locator`]));let au=O().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),ou=R([`npm`,`windows-installer`,`macos-dmg`]),su=P({version:au,installation:ou,phase:R([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:A().int().nonnegative(),downloadedBytes:A().int().nonnegative().optional(),totalBytes:A().int().positive().optional(),error:O().min(1).max(500).nullable(),serviceStopOutput:O().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});P({});let cu=O().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`);P({currentVersion:au,installation:ou.nullable(),latestVersion:au.nullable(),updateAvailable:j(),installationAvailable:j(),releaseNotes:O().min(1).max(2e4).nullable(),releaseNotesUrl:cu.nullable(),status:su.nullable(),error:O().min(1).max(500).nullable()}),P({status:su}),P({status:su.nullable()}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let lu=R([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);N({runningVersion:O().nullable(),installedVersion:O().nullable(),restartRequired:j(),remote:j(),updateSupported:j(),update:N({phase:lu,targetVersion:O().nullable(),error:O().nullable()})});let uu=N({version:O().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();N({hostname:O().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:A().int().min(1).max(65535).nullable(),identity:O().max(4096).nullable(),action:R([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:j().optional(),version:O().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),N({state:R([`installed`,`not-installed`])}).strict();let Q=O().min(1).max(1024),du={hostId:Q.regex(/^remote-(?:ssh(?:-|:)|control:)/u)},$={...du,threadId:Q},fu=I(`kind`,[P({kind:z(`hosts`)}),P({kind:z(`status`),...$}),P({kind:z(`list`),...du,cursor:O().nullable(),archived:j()}),P({kind:z(`read`),...$,page:P({cursor:O().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:R([`asc`,`desc`]).optional(),limit:A().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),P({kind:z(`usage`),...$,epoch:Q}),P({kind:z(`configure`),...$,epoch:Q,modelId:Q.optional(),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`),P({kind:z(`prompt`),...$,epoch:Q,text:O().min(1).max(8e3),requestId:Q.optional()}),P({kind:z(`interrupt`),...$,epoch:Q,turnId:Q}),P({kind:z(`rename`),...$,epoch:Q,name:O().min(1).max(512)}),P({kind:z(`archive`),...$,epoch:Q,archived:j()}),P({kind:z(`respond`),...$,epoch:Q,requestId:F([Q,A().int()]),result:L(O(),yo())})]),pu=O().min(1).max(1024),mu=N({hostId:pu,displayName:O().min(1).max(1024),source:R([`codex-managed`,`discovered`]),sshAlias:O().max(1024).nullable(),sshHost:O().min(1).max(1024),sshPort:A().int().min(1).max(65535).nullable(),identity:O().max(4096).nullable(),autoConnect:j(),connectionAnalyticsId:O().max(1024).optional()}),hu=P({displayName:O().min(1).max(1024),hostname:O().min(1).max(1024),sshPort:A().int().min(1).max(65535).nullable(),identity:O().max(4096).nullable()});I(`action`,[P({action:z(`session`),operation:fu}),P({action:z(`list`)}),P({action:z(`catalog`)}),P({action:z(`read-thread`),hostId:pu.refine(e=>e!==`local`),input:rl}),P({action:z(`save`),draft:hu,previous:mu.nullable()}),P({action:z(`remove`),previous:mu}),P({action:z(`connect`),hostId:pu,enabled:j()}),P({action:z(`state`),hostId:pu}),P({action:z(`runtime`),hostId:pu}),P({action:z(`update`),hostId:pu.refine(e=>e!==`local`),version:uu.shape.version})]),F([P({result:H}),P({error:P({code:A().int(),message:O()})})]),P({prompt:O().trim().min(1).max(2e3),cwd:O().max(4096).nullable()}),O().trim().min(1).max(60).nullable();let gu=O().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),_u=F([O(),N({en:O()}).catchall(O())]),vu=N({title:_u.optional(),description:_u.optional(),icon:O().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:O().optional()});N({extensions:M(N({id:gu,name:O().min(1).max(214),version:O().min(1).max(128),format:z(`dsh`),supportedTargets:ko([z(`web`)]),enabledTargets:M(z(`web`)).max(1),source:O().min(1).max(4096),projectUrl:O().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:O(),meta:vu.optional(),loadError:O().optional()})),loadedIds:M(gu),safeMode:j(),storeError:O().optional()});let yu=O().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);N({spec:O().trim().min(1).max(4096),registry:yu.optional()}).strict(),N({id:gu,enabled:j()}).strict(),N({id:gu}).strict(),z(1);function bu(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
122
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}}function qi(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Yi(t,`input`,e.processors),output:Yi(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function w(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return w(r.element,n);if(r.type===`set`)return w(r.valueType,n);if(r.type===`lazy`)return w(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return w(r.innerType,n);if(r.type===`intersection`)return w(r.left,n)||w(r.right,n);if(r.type===`record`||r.type===`map`)return w(r.keyType,n)||w(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:w(r.in,n)||w(r.out,n);if(r.type===`object`){for(let e in r.shape)if(w(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(w(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(w(e,n))return!0;return!!(r.rest&&w(r.rest,n))}return!1}let Ji=(e,t={})=>n=>{let r=Gi({...n,processors:t});return C(e,r),Ki(r,e),qi(r,e)},Yi=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Gi({...i??{},target:a,io:t,processors:n});return C(e,o),Ki(o,e),qi(o,e)},Xi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Zi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Xi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Qi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},$i=(e,t,n,r)=>{n.type=`boolean`},ea=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ta=(e,t,n,r)=>{n.not={}},na=(e,t,n,r)=>{let i=e._zod.def,a=Te(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ra=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ia=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},aa=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},oa=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=C(a.element,t,{...r,path:[...r.path,`items`]})},sa=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=C(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=C(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ca=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>C(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},la=(e,t,n,r)=>{let i=e._zod.def,a=C(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=C(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ua=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>C(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?C(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},da=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=C(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=C(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=C(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},fa=(e,t,n,r)=>{let i=e._zod.def,a=C(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},pa=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ma=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},ha=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},ga=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},_a=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;C(o,t,r);let s=t.seen.get(e);s.ref=o},va=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ya=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ba=(e,t,n,r)=>{let i=e._zod.innerType;C(i,t,r);let a=t.seen.get(e);a.ref=i},xa=/*@__PURE__*/ h(`ZodISODateTime`,(e,t)=>{Mn.init(e,t),O.init(e,t)});function Sa(e){return/* @__PURE__ */ ui(xa,e)}let Ca=/*@__PURE__*/ h(`ZodISODate`,(e,t)=>{Nn.init(e,t),O.init(e,t)});function wa(e){return/* @__PURE__ */ di(Ca,e)}let Ta=/*@__PURE__*/ h(`ZodISOTime`,(e,t)=>{Pn.init(e,t),O.init(e,t)});function Ea(e){return/* @__PURE__ */ fi(Ta,e)}let Da=/*@__PURE__*/ h(`ZodISODuration`,(e,t)=>{Fn.init(e,t),O.init(e,t)});function Oa(e){return/* @__PURE__ */ pi(Da,e)}let T=/*@__PURE__*/ h(`ZodError`,(e,t)=>{ot.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>lt(e,t)},flatten:{value:t=>ct(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ee,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ee,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ka=/* @__PURE__ */ ut(T),Aa=/* @__PURE__ */ dt(T),ja=/* @__PURE__ */ ft(T),Ma=/* @__PURE__ */ mt(T),Na=/* @__PURE__ */ gt(T),Pa=/* @__PURE__ */ _t(T),Fa=/* @__PURE__ */ vt(T),Ia=/* @__PURE__ */ yt(T),La=/* @__PURE__ */ bt(T),Ra=/* @__PURE__ */ xt(T),za=/* @__PURE__ */ St(T),Ba=/* @__PURE__ */ Ct(T),Va=/* @__PURE__ */ new WeakMap;function Ha(e,t,n){let r=Object.getPrototypeOf(e),i=Va.get(r);if(i||(i=/* @__PURE__ */ new Set,Va.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let E=/*@__PURE__*/ h(`ZodType`,(e,t)=>(x.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Yi(e,`input`),output:Yi(e,`output`)}}),e.toJSONSchema=Ji(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>ka(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ja(e,t,n),e.parseAsync=async(t,n)=>Aa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ma(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Na(e,t,n),e.decode=(t,n)=>Pa(e,t,n),e.encodeAsync=async(t,n)=>Fa(e,t,n),e.decodeAsync=async(t,n)=>Ia(e,t,n),e.safeEncode=(t,n)=>La(e,t,n),e.safeDecode=(t,n)=>Ra(e,t,n),e.safeEncodeAsync=async(t,n)=>za(e,t,n),e.safeDecodeAsync=async(t,n)=>Ba(e,t,n),Ha(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Ne(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ue(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rs(e,t))},superRefine(e,t){return this.check(is(e,t))},overwrite(e){return this.check(/* @__PURE__ */ Pi(e))},optional(){return Io(this)},exactOptional(){return Ro(this)},nullable(){return Bo(this)},nullish(){return Io(Bo(this))},nonoptional(e){return Ko(this,e)},array(){return M(this)},or(e){return F([this,e])},and(e){return Do(this,e)},transform(e){return Xo(this,Po(e))},default(e){return Ho(this,e)},prefault(e){return Wo(this,e)},catch(e){return Jo(this,e)},pipe(e){return Xo(this,e)},readonly(){return Qo(this)},describe(e){let t=this.clone();return Br.add(t,{description:e}),t},meta(...e){if(e.length===0)return Br.get(this);let t=this.clone();return Br.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Br.get(e)?.description},configurable:!0}),e)),Ua=/*@__PURE__*/ h(`_ZodString`,(e,t)=>{bn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ha(e,`_ZodString`,{regex(...e){return this.check(/* @__PURE__ */ Oi(...e))},includes(...e){return this.check(/* @__PURE__ */ ji(...e))},startsWith(...e){return this.check(/* @__PURE__ */ Mi(...e))},endsWith(...e){return this.check(/* @__PURE__ */ Ni(...e))},min(...e){return this.check(/* @__PURE__ */ Ei(...e))},max(...e){return this.check(/* @__PURE__ */ Ti(...e))},length(...e){return this.check(/* @__PURE__ */ Di(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Ei(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ ki(e))},uppercase(e){return this.check(/* @__PURE__ */ Ai(e))},trim(){return this.check(/* @__PURE__ */ Ii())},normalize(...e){return this.check(/* @__PURE__ */ Fi(...e))},toLowerCase(){return this.check(/* @__PURE__ */ Li())},toUpperCase(){return this.check(/* @__PURE__ */ Ri())},slugify(){return this.check(/* @__PURE__ */ zi())}})}),Wa=/*@__PURE__*/ h(`ZodString`,(e,t)=>{bn.init(e,t),Ua.init(e,t),e.email=t=>e.check(/* @__PURE__ */ Hr(Ga,t)),e.url=t=>e.check(/* @__PURE__ */ Jr(Ya,t)),e.jwt=t=>e.check(/* @__PURE__ */ li(fo,t)),e.emoji=t=>e.check(/* @__PURE__ */ Yr(Za,t)),e.guid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.uuid=t=>e.check(/* @__PURE__ */ Wr(qa,t)),e.uuidv4=t=>e.check(/* @__PURE__ */ Gr(qa,t)),e.uuidv6=t=>e.check(/* @__PURE__ */ Kr(qa,t)),e.uuidv7=t=>e.check(/* @__PURE__ */ qr(qa,t)),e.nanoid=t=>e.check(/* @__PURE__ */ Xr(Qa,t)),e.guid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.cuid=t=>e.check(/* @__PURE__ */ Zr($a,t)),e.cuid2=t=>e.check(/* @__PURE__ */ Qr(eo,t)),e.ulid=t=>e.check(/* @__PURE__ */ $r(to,t)),e.base64=t=>e.check(/* @__PURE__ */ oi(co,t)),e.base64url=t=>e.check(/* @__PURE__ */ si(lo,t)),e.xid=t=>e.check(/* @__PURE__ */ ei(no,t)),e.ksuid=t=>e.check(/* @__PURE__ */ ti(ro,t)),e.ipv4=t=>e.check(/* @__PURE__ */ ni(io,t)),e.ipv6=t=>e.check(/* @__PURE__ */ ri(ao,t)),e.cidrv4=t=>e.check(/* @__PURE__ */ ii(oo,t)),e.cidrv6=t=>e.check(/* @__PURE__ */ ai(so,t)),e.e164=t=>e.check(/* @__PURE__ */ ci(uo,t)),e.datetime=t=>e.check(Sa(t)),e.date=t=>e.check(wa(t)),e.time=t=>e.check(Ea(t)),e.duration=t=>e.check(Oa(t))});function D(e){return/* @__PURE__ */ Vr(Wa,e)}let O=/*@__PURE__*/ h(`ZodStringFormat`,(e,t)=>{S.init(e,t),Ua.init(e,t)}),Ga=/*@__PURE__*/ h(`ZodEmail`,(e,t)=>{Cn.init(e,t),O.init(e,t)}),Ka=/*@__PURE__*/ h(`ZodGUID`,(e,t)=>{xn.init(e,t),O.init(e,t)}),qa=/*@__PURE__*/ h(`ZodUUID`,(e,t)=>{Sn.init(e,t),O.init(e,t)});function Ja(e){return/* @__PURE__ */ Wr(qa,e)}let Ya=/*@__PURE__*/ h(`ZodURL`,(e,t)=>{wn.init(e,t),O.init(e,t)});function Xa(e){return/* @__PURE__ */ Jr(Ya,e)}let Za=/*@__PURE__*/ h(`ZodEmoji`,(e,t)=>{Tn.init(e,t),O.init(e,t)}),Qa=/*@__PURE__*/ h(`ZodNanoID`,(e,t)=>{En.init(e,t),O.init(e,t)}),$a=/*@__PURE__*/ h(`ZodCUID`,(e,t)=>{Dn.init(e,t),O.init(e,t)}),eo=/*@__PURE__*/ h(`ZodCUID2`,(e,t)=>{On.init(e,t),O.init(e,t)}),to=/*@__PURE__*/ h(`ZodULID`,(e,t)=>{kn.init(e,t),O.init(e,t)}),no=/*@__PURE__*/ h(`ZodXID`,(e,t)=>{An.init(e,t),O.init(e,t)}),ro=/*@__PURE__*/ h(`ZodKSUID`,(e,t)=>{jn.init(e,t),O.init(e,t)}),io=/*@__PURE__*/ h(`ZodIPv4`,(e,t)=>{In.init(e,t),O.init(e,t)}),ao=/*@__PURE__*/ h(`ZodIPv6`,(e,t)=>{Ln.init(e,t),O.init(e,t)}),oo=/*@__PURE__*/ h(`ZodCIDRv4`,(e,t)=>{Rn.init(e,t),O.init(e,t)}),so=/*@__PURE__*/ h(`ZodCIDRv6`,(e,t)=>{zn.init(e,t),O.init(e,t)}),co=/*@__PURE__*/ h(`ZodBase64`,(e,t)=>{Vn.init(e,t),O.init(e,t)}),lo=/*@__PURE__*/ h(`ZodBase64URL`,(e,t)=>{Un.init(e,t),O.init(e,t)}),uo=/*@__PURE__*/ h(`ZodE164`,(e,t)=>{Wn.init(e,t),O.init(e,t)}),fo=/*@__PURE__*/ h(`ZodJWT`,(e,t)=>{Kn.init(e,t),O.init(e,t)}),po=/*@__PURE__*/ h(`ZodNumber`,(e,t)=>{qn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r),Ha(e,`ZodNumber`,{gt(e,t){return this.check(/* @__PURE__ */ Si(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},min(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},lt(e,t){return this.check(/* @__PURE__ */ bi(e,t))},lte(e,t){return this.check(/* @__PURE__ */ xi(e,t))},max(e,t){return this.check(/* @__PURE__ */ xi(e,t))},int(e){return this.check(A(e))},safe(e){return this.check(A(e))},positive(e){return this.check(/* @__PURE__ */ Si(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Ci(0,e))},negative(e){return this.check(/* @__PURE__ */ bi(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ xi(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ wi(e,t))},step(e,t){return this.check(/* @__PURE__ */ wi(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function k(e){return/* @__PURE__ */ mi(po,e)}let mo=/*@__PURE__*/ h(`ZodNumberFormat`,(e,t)=>{Jn.init(e,t),po.init(e,t)});function A(e){return/* @__PURE__ */ hi(mo,e)}let ho=/*@__PURE__*/ h(`ZodBoolean`,(e,t)=>{Yn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r)});function j(e){return/* @__PURE__ */ gi(ho,e)}let go=/*@__PURE__*/ h(`ZodNull`,(e,t)=>{Xn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(e,t,n,r)});function _o(e){return/* @__PURE__ */ _i(go,e)}let vo=/*@__PURE__*/ h(`ZodUnknown`,(e,t)=>{Zn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function yo(){return/* @__PURE__ */ vi(vo)}let bo=/*@__PURE__*/ h(`ZodNever`,(e,t)=>{Qn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r)});function xo(e){return/* @__PURE__ */ yi(bo,e)}let So=/*@__PURE__*/ h(`ZodArray`,(e,t)=>{er.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),e.element=t.element,Ha(e,`ZodArray`,{min(e,t){return this.check(/* @__PURE__ */ Ei(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Ei(1,e))},max(e,t){return this.check(/* @__PURE__ */ Ti(e,t))},length(e,t){return this.check(/* @__PURE__ */ Di(e,t))},unwrap(){return this.element}})});function M(e,t){return/* @__PURE__ */ Bi(So,e,t)}let Co=/*@__PURE__*/ h(`ZodObject`,(e,t)=>{ar.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sa(e,t,n,r),_(e,`shape`,()=>t.shape),Ha(e,`ZodObject`,{keyof(){return R(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:yo()})},loose(){return this.clone({...this._zod.def,catchall:yo()})},strict(){return this.clone({...this._zod.def,catchall:xo()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Je(this,e)},safeExtend(e){return Ye(this,e)},merge(e){return Xe(this,e)},pick(e){return Ke(this,e)},omit(e){return qe(this,e)},partial(...e){return Ze(Fo,this,e[0])},required(...e){return Qe(Go,this,e[0])}})});function N(e,t){let n={type:`object`,shape:e??{},...v(t)};return new Co(n)}function P(e,t){return new Co({type:`object`,shape:e,catchall:xo(),...v(t)})}let wo=/*@__PURE__*/ h(`ZodUnion`,(e,t)=>{sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ca(e,t,n,r),e.options=t.options});function F(e,t){return new wo({type:`union`,options:e,...v(t)})}let To=/*@__PURE__*/ h(`ZodDiscriminatedUnion`,(e,t)=>{wo.init(e,t),cr.init(e,t)});function I(e,t,n){return new To({type:`union`,options:t,discriminator:e,...v(n)})}let Eo=/*@__PURE__*/ h(`ZodIntersection`,(e,t)=>{lr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>la(e,t,n,r)});function Do(e,t){return new Eo({type:`intersection`,left:e,right:t})}let Oo=/*@__PURE__*/ h(`ZodTuple`,(e,t)=>{fr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ua(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function ko(e,t,n){let r=t instanceof x;return new Oo({type:`tuple`,items:e,rest:r?t:null,...v(r?n:t)})}let Ao=/*@__PURE__*/ h(`ZodRecord`,(e,t)=>{gr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>da(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function L(e,t,n){return!t||!t._zod?new Ao({type:`record`,keyType:D(),valueType:e,...v(t)}):new Ao({type:`record`,keyType:e,valueType:t,...v(n)})}let jo=/*@__PURE__*/ h(`ZodEnum`,(e,t)=>{_r.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>na(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})}});function R(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new jo({type:`enum`,entries:n,...v(t)})}let Mo=/*@__PURE__*/ h(`ZodLiteral`,(e,t)=>{vr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ra(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function z(e,t){return new Mo({type:`literal`,values:Array.isArray(e)?e:[e],...v(t)})}let No=/*@__PURE__*/ h(`ZodTransform`,(e,t)=>{yr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aa(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(it(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(it(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Po(e){return new No({type:`transform`,transform:e})}let Fo=/*@__PURE__*/ h(`ZodOptional`,(e,t)=>{xr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Fo({type:`optional`,innerType:e})}let Lo=/*@__PURE__*/ h(`ZodExactOptional`,(e,t)=>{Sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ro(e){return new Lo({type:`optional`,innerType:e})}let zo=/*@__PURE__*/ h(`ZodNullable`,(e,t)=>{Cr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bo(e){return new zo({type:`nullable`,innerType:e})}let Vo=/*@__PURE__*/ h(`ZodDefault`,(e,t)=>{wr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ma(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ho(e,t){return new Vo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Uo=/*@__PURE__*/ h(`ZodPrefault`,(e,t)=>{Er.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ha(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wo(e,t){return new Uo({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Go=/*@__PURE__*/ h(`ZodNonOptional`,(e,t)=>{Dr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ko(e,t){return new Go({type:`nonoptional`,innerType:e,...v(t)})}let qo=/*@__PURE__*/ h(`ZodCatch`,(e,t)=>{kr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ga(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jo(e,t){return new qo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let Yo=/*@__PURE__*/ h(`ZodPipe`,(e,t)=>{Ar.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.in=t.in,e.out=t.out});function Xo(e,t){return new Yo({type:`pipe`,in:e,out:t})}let Zo=/*@__PURE__*/ h(`ZodReadonly`,(e,t)=>{Mr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>va(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qo(e){return new Zo({type:`readonly`,innerType:e})}let $o=/*@__PURE__*/ h(`ZodLazy`,(e,t)=>{Pr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ba(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function es(e){return new $o({type:`lazy`,getter:e})}let ts=/*@__PURE__*/ h(`ZodCustom`,(e,t)=>{Fr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ia(e,t,n,r)});function ns(e,t){return/* @__PURE__ */ Vi(ts,e??(()=>!0),t)}function rs(e,t={}){return/* @__PURE__ */ Hi(ts,e,t)}function is(e,t){return/* @__PURE__ */ Ui(e,t)}function as(e){return(t,n)=>{for(let r of e)Object.hasOwn(t,r)&&t[r]===void 0&&n.addIssue({code:`custom`,path:[r],message:`Explicit undefined is not valid JSON`})}}let os=F([D(),k(),j(),_o()]);function ss(e){let t=/* @__PURE__ */ new WeakSet,n=[{value:e,leaving:!1}];try{for(;n.length>0;){let e=n.pop();if(!e)break;if(e.leaving)t.delete(e.value);else if(typeof e.value==`object`&&e.value!==null){if(t.has(e.value))return!1;t.add(e.value),n.push({value:e.value,leaving:!0});for(let t of Object.values(e.value))n.push({value:t,leaving:!1})}}}catch{return!1}return!0}let cs=ns(ss,{message:`JSON value must not contain circular references`}),ls=es(()=>F([os,M(ls),L(D(),ls)])),B=cs.pipe(ls);cs.pipe(M(ls));let us=cs.pipe(L(D(),ls)),ds=P({code:D().min(1),message:D().min(1),retryable:j(),diagnostic:D().min(1).optional(),stage:D().min(1).optional(),durationMs:k().int().nonnegative().optional(),stderrTail:D().min(1).optional()}).superRefine(as([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),fs=D().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),ps=e=>D().min(1).max(e).refine(e=>e.trim().length>0),ms=L(fs,N({label:ps(256).optional(),description:ps(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),hs=L(fs,ps(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),gs=D().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),V=gs.brand(),H=gs.brand(),_s=gs.brand();gs.brand(),gs.brand();let vs=D().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),U=vs.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),ys=N({modes:M(N({id:U,label:vs.max(256),description:vs.max(1024).optional(),dangerous:j().optional(),localizations:ms.optional()}).strict()).min(1).max(32),defaultModeId:U}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});N({threadId:H,permissionModeId:U}).strict();let W=k().int().safe().nonnegative(),bs=k().finite().nonnegative(),xs=k().finite().min(0).max(100),Ss=N({version:F([z(3),z(4)]).optional(),requestId:D().min(1),turnId:D().min(1).max(1024),outputTokens:W,startedAtMs:W,completedAtMs:W}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Cs=N({version:F([z(2),z(3),z(4)]).optional(),value:bs,turnId:D().min(1).max(1024),at:W}).strict();N({outputTimings:M(Ss).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Cs.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Cs.extend({value:W}).optional()}).strict();let ws=e=>hs.refine(t=>Object.values(t).every(t=>t.length<=e)),Ts=N({composerIndicators:M(N({kind:z(`countdown`),id:D().min(1).max(64),expiresAtUnix:W,label:ws(256).optional(),tooltip:ws(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:W.optional(),cachedInputTokens:W.optional(),cacheWriteInputTokens:W.optional(),outputTokens:W.optional(),outputTokensPerSecond:bs.optional(),sessionOutputTokensPerSecond:bs.optional(),apiOutputTokensPerSecond:bs.optional(),reasoningOutputTokens:W.optional(),totalTokens:W.optional(),totalCostUsd:bs.optional(),totalCredits:bs.optional(),contextUsagePercent:bs.optional(),cacheHitRatePercent:xs.optional(),contextWindowTokens:W.optional(),contextUsedTokens:W.optional(),planFiveHourUsedPercent:xs.optional(),planFiveHourResetsAtUnix:W.optional(),planSevenDayUsedPercent:xs.optional(),planSevenDayResetsAtUnix:W.optional(),sessionCacheHitRatePercent:xs.optional(),timeToFirstOutputMs:W.optional(),latestRequestTimeToFirstOutputMs:W.optional(),costSource:R([`publicPrice`,`native`]).optional(),unpricedModels:M(D().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),Es=k().finite().min(0).max(100),Ds=R([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),Os=N({id:D().min(1).max(256),label:D().min(1).max(256),localizations:ms.optional()}).strict(),ks=N({product:D().min(1),periodType:Ds.optional(),scope:Os.optional(),localizations:ms.optional(),used:k().finite().nonnegative().optional(),limit:k().finite().nonnegative().optional(),unit:D().min(1).max(32).optional(),usagePercent:Es,resetsAt:D().min(1).optional()}).strict(),As=N({availableCount:k().int().safe().positive(),nextExpiresAt:D().min(1).optional(),expiresAt:M(D().min(1)).min(1).max(32).optional()}).strict(),js=N({used:k().finite().nonnegative().optional(),limit:k().finite().nonnegative().optional(),unit:D().min(1).max(32).optional(),label:D().min(1).optional(),scope:Os.optional(),localizations:ms.optional(),usedPercent:Es,resetsAt:D().min(1).optional(),periodType:Ds,productUsage:M(ks).min(1).optional(),resetCredits:As.optional()}).strict(),Ms=N({amount:k().finite().nonnegative(),currency:D().trim().min(1).max(8),label:D().trim().min(1).max(128).optional()}).strict();N({threadId:H,refresh:z(`exact`).optional()}).strict(),N({threadId:H,usage:Ts.nullable(),accountCredits:js.optional(),accountBalance:Ms.optional(),accountCreditsSupported:j().optional()}).strict();let Ns=D().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ps=D().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Fs=R([`priority`,`ultrafast`]),G=N({id:Ps,serviceTier:Fs.optional()}).strict();function Is(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let K=Ns.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Ls=Ns.max(256),Rs=N({id:K,label:Ns.max(256)}).strict(),zs=N({ref:G,label:Ns.max(256),resolvedModelLabel:Ls.optional(),fastModel:G.optional(),supportedThinkingOptionIds:M(K).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function Bs(e,t){if(t)return e?.models.find(e=>Is(e.ref,t)||Is(e.fastModel,t))}let Vs=M(Rs).superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Thinking option IDs must be unique`,path:[r,`id`]}),n.add(i.id)}),Hs=N({models:M(zs),defaultModel:G.optional(),thinkingOptions:Vs,defaultThinkingOptionId:K.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>Is(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>Is(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!Bs(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),Us=N({fork:j(),forkAcrossCwd:j(),rollbackLastTurn:j()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Ws=R([`live`,`atCreate`]),Gs=N({configuration:N({selectModel:j(),selectThinkingOption:j(),selectPermissionMode:j(),permissionModeScope:Ws.default(`live`)}).strict(),history:Us,subagents:N({observe:j(),readTranscript:j()}).strict().optional(),autonomousTurns:N({observe:j()}).strict().optional(),steer:j().optional(),persistentPlan:j().optional()}).strict();N({effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),availableThinkingOptions:Vs.optional(),effectivePermissionModeId:U.optional()}).strict().superRefine((e,t)=>{e.effectiveThinkingOptionId&&e.availableThinkingOptions&&!e.availableThinkingOptions.some(({id:t})=>t===e.effectiveThinkingOptionId)&&t.addIssue({code:`custom`,message:`Effective Thinking option must be currently available`,path:[`effectiveThinkingOptionId`]})});let Ks=N({open:z(!0)}).strict();F([N({status:z(`ready`),catalog:Hs,permissionModes:ys.optional(),capabilities:Gs,webUi:Ks.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),N({status:R([`notInstalled`,`unavailable`,`error`]),error:ds}).strict()]),N({harnessId:V,cwd:Ns.max(16384).optional(),refresh:j().optional(),purpose:z(`availability`).optional(),credentialAccess:R([`allow`,`retry`]).optional()}).strict(),N({harnessId:V}).strict(),N({}).strict(),N({threadId:H,model:G}).strict(),N({threadId:H,thinkingOptionId:K}).strict(),N({threadId:H,includeReferenceCapability:j().optional()}).strict(),I(`owner`,[N({owner:z(`codex`),locked:j(),effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),effectivePermissionModeId:U.optional(),history:Us.optional(),supportsThreadReferences:z(!0).optional()}).strict(),N({owner:z(`external`),harnessId:Ns.max(256),transportModelId:Ns.max(8192),effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),availableThinkingOptions:Vs.optional(),effectivePermissionModeId:U.optional(),history:Us,usage:Ts.optional(),locked:z(!0)}).strict()]),N({threadIds:M(H).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let qs=I(`owner`,[N({threadId:H,owner:z(`codex`)}).strict(),N({threadId:H,owner:z(`external`),harnessId:D().max(256).pipe(V)}).strict()]);N({threads:M(qs).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),N({threadId:H,text:D().optional()}).strict(),N({kind:z(`application`),value:D().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),xe}}).pipe(N({expectedTurnId:_s,clientUserMessageId:D().min(1),delivery:R([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),R([`activeTurn`,`newTurn`]),N({delivery:R([`official`,`activeTurn`,`newTurn`])}).strict();let Js=D().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),Ys=Js.pipe(V),Xs=Ys.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Zs=D().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),Qs=Xa().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),$s=N({en:D().max(4096),"zh-CN":D().max(4096).optional()}).strict(),ec=N({commands:M(N({terminal:D().max(256),command:D().max(4096)}).strict()).max(8),before:$s.optional(),after:$s.optional(),downloads:M(N({label:D().max(128),url:Qs}).strict()).max(8).optional()}).strict(),tc={id:Ys,name:D().trim().min(1).max(128),version:D().min(1).max(128),kind:z(`usage`).optional(),iconStyle:N({vector:N({viewBox:D().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:D().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:M(N({d:D().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:R([`evenodd`,`nonzero`]).optional(),fill:D().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:D().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:k().min(0).max(50).optional(),paddingRatio:k().min(0).max(.25).optional()}).strict().optional(),installation:ec.optional(),notice:$s.optional(),launchCommand:z(!0).optional(),links:N({website:Qs.optional(),documentation:Qs.optional(),installation:Qs.optional()}).strict().optional()};N({manifestVersion:z(1),...tc,adapterApiVersion:k().int().positive(),entry:Zs,icon:Zs.optional()}).strict();let nc=D().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),rc=N({...tc,icon:nc.optional()}).strict();N({}).strict(),N({plugins:M(rc.extend({id:Xs})).max(128)}).strict(),N({version:z(1),enabled:M(Ys).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let ic=Js,ac=R([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),oc=R([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),sc=D().trim().min(1).max(128);function cc(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let lc=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),uc=Zs.refine(e=>cc(e)!==void 0&&lc(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),dc=D().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Xa({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function fc(e){return P({en:e,"zh-CN":e})}let pc=fc(D().trim().min(1)),mc=M(oc).max(oc.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),hc=M(ac).max(ac.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),gc={key:D().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:pc,description:pc.optional()},_c={...gc,step:k().positive().optional(),default:k().optional()},vc=P({value:D(),label:pc}),yc=I(`type`,[P({...gc,type:z(`boolean`),default:j().optional()}),P({...gc,type:z(`string`),placeholder:pc.optional(),default:D().optional()}),P({..._c,type:z(`number`),min:k().optional(),max:k().optional()}),P({..._c,type:z(`range`),min:k(),max:k()}),P({...gc,type:z(`select`),options:M(vc).min(1),default:D().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),bc=N({manifestVersion:A().positive(),id:ic,name:F([sc,fc(sc)]),version:D().min(1).max(128),desktopApi:A().positive()}).passthrough().extend({manifestVersion:z(1),desktopApi:z(1),description:P({en:D().max(4096),"zh-CN":D().max(4096).optional()}).optional(),author:D().trim().min(1).max(128).optional(),repository:dc.optional(),details:P({en:D().max(16384),"zh-CN":D().max(16384).optional()}).optional(),icon:uc.optional(),screenshots:M(uc).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:P({script:Zs,style:Zs.optional()}).optional(),backend:P({script:Zs.refine(lc)}).optional(),slots:hc.default(()=>[]),settingsSchema:M(yc).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:mc.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),xc=D().regex(/^[a-f0-9]{64}$/u),Sc=P({state:R([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:xc.optional(),error:D().optional(),conflictWith:ic.optional()});P({controllerPid:A().positive(),targetId:D().nullable(),updatedAt:Sa(),handledReloadToken:Ja().optional(),extensions:L(D(),Sc),surfaces:L(D(),Sc).optional()});let Cc=R([`official`,`community`]);function wc(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Tc=dc.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||wc(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),Ec=P({id:ic,version:D().trim().min(1).max(128),name:pc.extend({en:sc,"zh-CN":sc}),description:fc(D().trim().min(1).max(4096)),details:fc(D().trim().min(1).max(16384)).optional(),author:D().trim().min(1).max(128),repository:dc,stars:k().int().min(0).optional(),downloads:k().int().min(0).optional(),categories:mc.optional(),trustTier:Cc.default(`community`),icon:dc.optional(),screenshots:M(dc).max(4).optional(),downloadUrl:Tc,sha256:xc,slots:hc.optional(),publishedAt:D().optional(),updatedAt:D().optional(),minCodexHostVersion:D().optional()});P({schemaVersion:z(1),generatedAt:D(),extensions:M(Ec).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Dc=D().trim().min(1).max(128),Oc=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,kc=ic.refine(e=>!Oc.test(e),`Reserved extension ID`),Ac=R([`desktop`,`web`]),jc=xc,Mc=Ja(),Nc=Zs.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Oc.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),Pc=bc.shape,Fc=(e,t=0)=>P({en:D().trim().min(t).max(e),"zh-CN":D().trim().min(t).max(e)}),Ic=e=>Nc.refine(t=>t.endsWith(e),`Expected a ${e} file`),Lc=Ic(`.mjs`),Rc=Ic(`.css`).optional(),zc=e=>e.normalize(`NFC`).toLowerCase(),Bc=P({manifestVersion:z(2),id:kc,name:Fc(128,1),version:D().trim().min(1).max(128),description:Fc(4096),details:Fc(16384).optional(),author:Pc.author,repository:Pc.repository,icon:Pc.icon.refine(e=>e===void 0||Nc.safeParse(e).success),screenshots:Pc.screenshots.refine(e=>e===void 0||e.every(e=>Nc.safeParse(e).success)),categories:Pc.categories,settingsSchema:Pc.settingsSchema,slots:Pc.slots.removeDefault().optional(),page:P({apiVersion:z(1),entry:Lc,style:Rc,title:Fc(128,1).optional()}).optional(),widget:P({apiVersion:z(1),entry:Lc,style:Rc}).optional(),desktop:P({apiVersion:z(1),script:Ic(`.js`),style:Rc}).optional(),web:P({apiVersion:z(1),entry:Lc.optional(),style:Rc}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:P({apiVersion:z(1),entry:Lc}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||zc(e)!==zc(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Vc({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let Hc=Dc,q=A().nonnegative(),Uc=P({revision:q,enabled:M(kc).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)}),{downloadUrl:Wc,...Gc}=Ec.shape,Kc=N({...Gc,id:kc,format:z(`codexhost`),targets:M(Ac).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:P({page:A().positive().optional(),widget:A().positive().optional(),desktop:A().positive().optional(),web:A().positive().optional(),backend:A().positive().optional()}),downloadUrl:Wc.refine(e=>e.startsWith(`https://`),`Expected HTTPS`)}).refine(({targets:e,apis:t})=>{let n=Vc({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);N({schemaVersion:z(2),generatedAt:D().min(1),extensions:M(Kc).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:dc,fetchedAt:Sa(),cached:j()});let qc={id:kc},Jc={...qc,activationId:Mc,digest:jc},Yc={...qc,activationId:Jc.activationId.optional()},Xc=D().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),Zc=D().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function Qc(e){return D().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let $c=P({type:z(`github`),repository:D().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Zc.optional(),tag:Zc.optional(),asset:D().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Nc.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),el=F([P({type:z(`catalog`),...qc}),$c,P({type:z(`zip`),base64:Qc(67108864).min(4)}),P({type:z(`zip`),localZipPath:Xc}),P({type:z(`localDir`),localDir:Xc})]),tl=I(`type`,[P({type:z(`catalog`),...qc}),$c,P({type:z(`zip`)}),P({type:z(`localDir`)})]),nl=P({...Jc,manifest:Bc,installedAt:Sa(),source:tl.optional()}),rl=e=>D().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),il={desktopConflictWith:kc.optional()},al=R([`none`,`inactive`,`starting`,`running`,`failed`]),ol=I(`state`,[nl.extend({state:z(`valid`),enabled:j(),...il,iconDataUrl:rl(131072).optional(),screenshotDataUrls:M(rl(524288)).max(4).optional(),backendState:al.optional(),backendError:D().optional()}),P({state:R([`invalid`,`incompatible`]),id:D().min(1),enabled:j(),error:D()})]);P({revision:q,configuration:Uc,diagnostics:M(D()),extensions:M(ol)}),P({revision:q,extensions:M(nl.extend({...il,settingsRevision:q})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`},sl=Object.freeze(Object.values(J));new Set(sl),P({});let cl={expectedRevision:q};P({...qc,...cl}),nl.extend({replaced:j()}),I(`state`,[P({state:z(`saved`),configuration:Uc}),P({state:z(`revision-conflict`),revision:q})]),P({...Yc,digest:Jc.digest.optional(),path:Nc}),P({mimeType:D().min(1),base64:Qc(16777216),digest:Jc.digest}),P({settingsRevision:q,values:us}),J.list,J.snapshot,J.catalog,P({forceRefresh:j().optional()}),J.install,P({source:el}),J.update,P({...qc,expectedDigest:Jc.digest,expectedActivationId:Jc.activationId.optional(),source:el.optional()}),J.enable,J.disable,J.uninstall,P({...qc,removeData:j().optional(),expectedDigest:Jc.digest.optional()}),P({...qc,removed:j()}),J.recover,P({expectedRevision:cl.expectedRevision.optional()}),J.asset,J.settingsGet,P(Yc),J.settingsSet,P({...Yc,expectedSettingsRevision:q,values:us}),J.backendInvoke,P({...Yc,method:Hc,params:B.optional()}),P({result:B}),N({threadId:H}).strict(),N({confirmed:j()}).strict(),[...sl],N({threadIds:M(D().min(1))}).strict(),N({threadId:D().min(1).max(1024),pinned:j()}).strict(),N({}).strict(),N({parents:L(D().min(1),D().min(1))}).strict(),N({prompt:D().max(16384).optional()}).strict(),N({projects:M(N({id:D(),name:D(),rootPaths:M(D())})),assignments:L(D(),D()),projectless:M(D()),pinned:M(D())});let ll=L(D(),yo()),ul=N({epoch:D().uuid(),sequence:k().int().nonnegative()});I(`type`,[N({type:z(`skills-changed`),cursor:ul,cwd:D().optional()}),N({type:z(`harness-inspection-changed`),cursor:ul,harnessId:D().min(1)}),N({type:z(`display-settings-changed`),cursor:ul}),N({type:z(`preferences-changed`),cursor:ul,revision:k().int().nonnegative()}),N({type:z(`extensions-changed`),cursor:ul,revision:q}),N({type:z(`hello`),version:z(1),cursor:ul,reset:j()}),N({type:z(`changed`),cursor:ul,threadId:D().min(1),method:D().min(1)})]);let dl=I(`type`,[N({type:z(`text`),id:D(),prompt:D(),secret:j().optional(),optional:j().optional()}),N({type:z(`choice`),id:D(),prompt:D(),multiple:j(),allowOther:j(),optional:j().optional(),options:M(N({value:D(),label:D(),description:D().optional()}))})]),fl=I(`type`,[N({type:z(`approval`),title:D(),description:D().optional(),subject:yo().optional(),actions:M(N({id:D(),label:D(),effect:D()}))}),N({type:z(`question`),title:D().optional(),questions:M(dl)})]),pl=N({requestId:F([D(),k().int()]),threadId:D(),kind:R([`approval`,`question`]),interaction:fl,request:ll}),ml=N({id:D().min(1),clientUserMessageId:D().min(1),input:M(ll),presentationInput:M(ll).nullable().optional()}).passthrough();N({fields:M(N({path:M(F([D(),k().int().nonnegative()])),originalLength:k().int().nonnegative()}))});let hl=N({id:D().min(1),status:D().min(1),codexhostTurnOutcome:N({status:z(`unknown`),reason:D()}).optional(),items:M(N({id:D().min(1),type:D().min(1)}).passthrough()),codexhostFileOperations:M(N({beforeItemId:D().nullable(),item:N({id:D().min(1),type:D().min(1)}).passthrough()})).optional(),error:N({message:D().optional()}).passthrough().nullable().optional(),fingerprint:D().min(1).optional(),unchanged:z(!0).optional()}).passthrough(),gl=N({id:D().min(1).max(512),fingerprint:D().min(1).max(128)});N({threadId:D().min(1),knownTurns:M(gl).max(64).optional(),truncateToolOutput:j().optional()});let _l=N({harnessId:D().min(1),nativeSessionId:D().min(1)});N({cursor:ul,activeTurnId:D().min(1).nullable().optional(),command:N({name:D().min(1),turn:hl,subsequentTurnId:D().min(1).optional()}).optional(),thread:N({id:D().min(1),cwd:D(),modelProvider:D().min(1),createdAt:k(),updatedAt:k(),status:N({type:D()}).passthrough(),name:D().nullable().optional(),preview:D().optional(),codexhostImportSource:_l.optional(),turns:M(hl).length(0)}).passthrough(),turnsPage:N({data:M(hl).max(5),nextCursor:D().nullable()}),configuration:N({native:N({model:D().min(1).max(1024).optional(),reasoningEffort:D().min(1).max(128).optional()}).optional(),effectiveModel:G.optional(),effectiveThinkingOptionId:K.optional(),effectivePermissionModeId:U.optional()}),queue:N({items:M(ml),pausedReason:R([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:M(pl)}),N({version:z(1),owner:z(`service`).optional(),pid:k().int().positive(),port:k().int().min(1).max(65535),token:D().regex(/^[0-9a-f]{64}$/u),startedAt:k(),epoch:D().uuid()}),N({epoch:D().uuid(),threadId:D().min(1),requestId:F([D(),k().int()]),result:ll}),N({includeArchived:j().optional(),officialCursor:N({live:D().nullable(),archived:D().nullable().optional()}).strict().optional()}).strict(),N({threads:M(us),ownership:M(qs),archivedThreadIds:M(H),officialCursor:N({live:D().nullable(),archived:D().nullable().optional()}).strict().optional()}).strict();let vl=R([`running`,`waiting`,`idle`,`unknown`]),yl=P({harnessId:V,title:D().optional(),status:vl,archived:j()}),bl=P({revision:A().nonnegative(),parents:L(H,H),nodes:L(H,yl),truncated:j()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,nodes:t})=>Object.entries(e).every(([e,n])=>Object.hasOwn(t,e)&&Object.hasOwn(t,n)),`Missing Thread tree node`),xl=D().min(1).max(128);P({});let Sl=P({subscriptionId:xl});P({}),Sl.extend({snapshot:bl});let Cl=D().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);N({available:j()}).strict(),N({path:D().min(1),mimeType:Cl}).strict();let wl=R([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);I(`ok`,[N({ok:z(!0),text:D()}).strict(),N({ok:z(!1),error:N({code:wl}).strict()}).strict()]),N({threadId:H.optional(),cwd:D().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Tl=N({name:D().min(1).regex(/^[^\s[\]]+$/u),description:D().optional(),path:D().min(1),scope:R([`project`,`global`]),source:D().min(1)}).strict();N({revision:k().int().nonnegative(),complete:j(),skills:M(Tl),warnings:M(D()).optional()}).strict(),N({cwd:D().min(1).optional()}).strict();let El=N({kind:R([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:D().min(1)}).strict(),Dl=I(`status`,[N({status:z(`not-installed`)}),N({status:z(`not-running`)}),N({status:z(`not-logged-in`)}),N({status:z(`https-disabled`)}),N({status:z(`not-serving`),command:D()}),N({status:z(`occupied`),target:D()}),N({status:z(`serving`),url:D(),funnel:j()}),N({status:z(`error`),message:D()})]);N({state:Dl,error:D().optional()}).strict();let Ol=I(`status`,[N({status:z(`on`)}),N({status:z(`off`)}),N({status:z(`invalid`),reason:D()})]),kl=N({lan:j(),autostart:Ol}).strict(),Al=N({expiresAt:D().optional(),issuing:j(),failure:N({detail:D().optional(),retryAt:D(),paused:j()}).optional()}),jl=I(`status`,[N({status:z(`off`),reason:R([`invite`,`name-taken`,`banned`]).optional()}),N({status:z(`connecting`),reason:R([`full`,`unreachable`]).optional()}),N({status:z(`connected`),url:D(),certificate:Al}),N({status:z(`missing-certificate`),url:D(),certificate:Al}),N({status:z(`stopped`),reason:R([`replaced`,`rejected`,`unsupported-version`])})]);D().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),D().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let Ml=R([`official`,`self-hosted`]);N({secret:D().min(1),lastUsedAt:k().nullable(),networkUrls:M(El),directCandidates:M(El).optional(),tailscale:Dl,background:kl.optional(),relay:N({state:jl,enabled:j(),kind:Ml,officialHost:D(),customHost:D().optional(),officialHostname:D().optional(),customHostname:D().optional(),quotaUntil:D().optional()}).strict().optional()}).strict();let Nl=P({threadId:D().min(1).max(1024),view:R([`result`,`messages`]),from:k().int().min(1).max(2**53-1).optional(),to:k().int().min(1).max(2**53-1).optional()}),Pl=N({id:D().min(1).max(256),harnessId:D().min(1),label:D().min(1).max(512),provider:R([`openai-codex`,`xai`])}).strict(),Fl=D().regex(/^[a-z][a-z0-9-]{0,47}$/),Il=N({name:Fl,source:Pl,importedAt:D()}).strict(),Ll=I(`action`,[N({action:z(`list`)}).strict(),N({action:z(`import`),sourceId:D().min(1).max(256),name:Fl,confirmed:z(!0)}).strict(),N({action:z(`reimport`),sourceId:D().min(1).max(256),name:Fl,confirmed:z(!0)}).strict(),N({action:z(`remove`),name:Fl,confirmed:z(!0)}).strict()]),Rl=N({provider:D().min(1).max(128),type:R([`oauth`,`api_key`,`unknown`]),label:D().min(1).max(512).optional(),vendor:R([`openai-codex`,`xai`]).optional()}).strict();N({sources:M(Pl),targets:M(N({harnessId:D(),providers:M(R([`openai-codex`,`xai`])),imports:M(Il),others:M(Rl).default([])}).strict())}).strict(),N({targetHarnessId:D().min(1).max(128).optional(),request:Ll}).strict(),N({events:j()});let zl=M(P({agent:D().min(1).max(128),section:R([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);P({entries:zl.nullable()}),P({}),P({entries:zl,initializeOnly:j().optional()});let Bl=P({enabled:j(),timeoutMinutes:k().int().min(5).max(1440)});Object.freeze({enabled:!1,timeoutMinutes:10});let Vl=D().regex(/^external$/u),Hl=V.transform(e=>String(e)),Ul=P({model:G.optional(),thinkingOptionId:K.optional(),permissionModeId:U.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),Wl=P({lastHarness:V.optional(),byHarness:L(Hl,Ul)}),Gl=P({model:G.optional(),thinkingOptionId:K.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Kl=P({byHarness:L(Hl,Gl)}),ql=D().min(1).max(1024),Jl=P({idleRelease:Bl.optional(),favorites:L(Hl,M(ql).max(2048)).default({}),newThread:Wl.optional(),delegation:Kl.optional()});P({scope:Vl,revision:k().int().nonnegative(),values:Jl}),P({scope:Vl.default(`external`)});let Yl=I(`kind`,[P({kind:z(`idleRelease`),value:Bl}),P({kind:z(`favorite`),harnessId:V,modelId:ql,enabled:j()}),P({kind:z(`favorites`),harnessId:V,modelIds:M(ql).max(2048)}),P({kind:z(`newThread`),lastHarness:V.optional(),harnessId:V.optional(),configuration:Ul.optional()}),P({kind:z(`delegation`),harnessId:V,configuration:Gl.nullable()})]);P({scope:Vl.default(`external`),operations:M(Yl).min(1).max(256),initializeOnly:j().optional(),expectedRevision:k().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),P({version:z(1),revision:k().int().nonnegative(),scopes:L(Vl,Jl)});let Xl=k().finite().nonnegative(),Zl=P({input:Xl,output:Xl,cacheRead:Xl.optional(),cacheWrite:Xl.optional(),cacheWrite1h:Xl.optional()}),Ql=D().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);P({path:D(),entries:M(P({key:D(),price:Zl})),error:D().nullable()}),P({}),P({key:Ql,price:Zl.nullable(),previousKey:Ql.optional()}),P({model:Ql});let $l=P({official:j().optional(),canonicalModelId:D().min(1).optional(),provider:D().min(1).max(512),model:D().min(1).max(512),price:Zl});P({price:Zl.nullable(),suggestions:M($l).max(6).optional()});let eu=[`today`,`7d`,`30d`,`90d`,`all`],Y=k().int().min(0).max(2**53-1),tu=D().regex(/^\d{4}-\d{2}-\d{2}$/u),X=D().min(1).max(128),nu=D().min(1).max(512),ru=D().min(1).max(4096);P({range:R(eu),timeZone:D().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:X.optional(),model:nu.nullable().optional(),project:ru.nullable().optional(),date:tu.optional()});let iu=P({requests:Y,inputTokens:Y,cachedInputTokens:Y,cacheWriteInputTokens:Y,cacheKnownInputTokens:Y,cacheHitCachedInputTokens:Y,cacheHitInputTokens:Y,outputTokens:Y,reasoningOutputTokens:Y,costUsd:k().finite().min(0),unpricedRequests:Y,unmeteredRequests:Y}),au=iu.shape,ou=P({harness:X,sessionId:D().min(1).max(512),project:ru.nullable(),title:D().min(1).max(200).optional(),models:M(nu).max(16),firstAtMs:Y,lastAtMs:Y,...au});P({range:R(eu),from:tu.nullable(),to:tu,filters:P({harness:X.nullable(),model:nu.nullable(),unknownModel:j(),project:ru.nullable(),unknownProject:j(),date:tu.nullable()}),reading:P({complete:j(),sources:Y,read:Y}),failures:M(P({harness:X,message:D().max(2048)})).max(256),options:P({harnesses:M(X).max(256),models:M(nu.nullable()).max(4096),projects:M(ru.nullable()).max(4096)}),modelLabels:M(P({harness:X,model:nu,label:nu})).max(4096).optional(),credits:M(P({harness:X,model:nu.nullable(),credits:k().finite().min(0),reportedRequests:Y,requests:Y})).max(4096).optional(),totals:iu,daily:M(P({date:tu,harness:X,...au})).max(2e5),hourly:M(P({weekday:k().int().min(0).max(6),hour:k().int().min(0).max(23),...au})).max(168),byHarness:M(P({harness:X,...au})).max(256),byModel:M(P({model:nu.nullable(),...au,harnessPricedRequests:Y})).max(4096),byProject:M(P({project:ru.nullable(),...au})).max(4096),sessions:M(ou).max(100),recentSessions:M(ou).max(100).optional()}),N({threadId:H}),N({discarded:j()});let su=I(`type`,[N({id:D().min(1),type:z(`choice`),prompt:D(),options:M(N({value:D().min(1),label:D(),description:D().optional()})).min(1),multiple:j(),allowOther:j(),optional:j()}),N({id:D().min(1),type:z(`text`),prompt:D(),multiline:j(),secret:z(!1),optional:j(),placeholder:D().optional(),prefill:D().optional()})]),cu=N({interactionId:D().min(1),turnId:D().min(1),title:D().optional(),questions:M(su).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});P({threadId:D().min(1)}),N({questions:M(cu)}),P({threadId:D().min(1),turnId:D().min(1),interactionId:D().min(1),answers:L(D(),M(D())),cancelled:j().default(!1)}),N({accepted:z(!0)});let lu=/* @__PURE__ */ new Set([`codexhostTurnChanges`,`codexhostToolOutput`]),uu=N({path:D(),oldText:D().nullable(),newText:D()});N({sessionId:D().min(1),turn:k().int().nonnegative(),path:D().min(1).optional()}),N({diffs:M(uu)}),P({}),P({}),N({reference:N({sessionId:D().min(1),epoch:D().min(1),turn:k().int().nonnegative(),seq:k().int().nonnegative(),callId:D().min(1),part:k().int().nonnegative(),version:D().min(1)}),length:k().int().nonnegative(),bytes:k().int().nonnegative()}),P({title:D().trim().min(1).max(200),type:R([`info`,`warning`,`danger`]),body:D().trim().min(1).max(16384)}),P({}),P({url:D().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status`.split(`.`));let du=R([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),fu=R([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);P({threadId:D(),title:D(),harnessId:D(),state:du,reason:fu,inactiveMs:k().nonnegative()}),P({threadId:H,turnId:_s});let pu=N({email:D().trim().min(1).max(320).optional(),label:D().trim().min(1).max(256).optional(),plan:D().trim().min(1).max(128).optional(),credits:js.optional(),balance:Ms.optional()}).strict();function mu(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 hu=mu(pu),gu={harnessId:V,harnessName:D().trim().min(1).max(128)},_u=N(gu).strict();N({}).strict(),N({sources:M(_u).max(128)}).strict(),N({harnessId:V,refresh:j().optional()}).strict(),N({...gu,account:hu.nullable(),accounts:M(hu).max(8).optional()}).strict(),N({refresh:j().optional()}).strict(),N({accounts:M(mu(pu.extend(gu))).max(128)}).strict(),N({harnessId:Xs,model:G.optional(),thinkingOptionId:K.optional(),permissionModeId:U.optional(),prewarm:z(!0).optional()}).strict();let vu=D().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);N({harnessId:Xs}).strict().extend({path:vu.nullable()}),N({path:vu.nullable(),restartRequired:j()}).strict(),N({harnessId:V,action:R([`check`,`update`,`install`])}).strict();let yu=N({currentVersion:D().min(1).max(128),latestVersion:D().min(1).max(128),updateAvailable:j(),canUpdate:j(),versionKind:R([`cli`,`application`]).optional(),manualUpdateUrl:Xa().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:D().max(2048).optional(),messageCode:D().min(1).max(128).optional(),notice:hs.optional(),latestVersionKind:R([`unknown`,`tracking-branch`]).optional()}).strict();N({taskId:D().uuid()}).strict(),I(`status`,[N({taskId:D().uuid(),status:z(`running`)}).strict(),N({taskId:D().uuid(),status:z(`succeeded`),result:yu}).strict(),N({taskId:D().uuid(),status:z(`failed`),error:N({code:k().int(),message:D().min(1).max(2048)}).strict()}).strict()]);let bu=D().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),xu=D().trim().min(1),Su=R([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),Cu=N({accountId:bu,label:xu.max(256),email:D().email().max(320).optional(),planType:Su.optional()}).strict(),wu=R([`ready`,`unavailable`]);N({version:z(2),currentAccountId:bu.nullable(),phase:wu,revision:k().int().nonnegative(),instanceId:xu.max(1024).optional(),accounts:M(Cu).max(1)}).strict(),N({accountId:bu,refresh:j().optional()}).strict(),N({accountId:bu,usage:Ts.nullable(),accountCredits:js.optional(),freshness:R([`live`,`cached`]),observedAt:D().datetime().nullable()}).strict();let Tu=1e3,Eu=D().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Du=Eu.max(1024),Ou=N({nativeSessionId:Du,title:Eu.max(4096).nullable(),updatedAt:k().int().nonnegative().max(864e13),cwd:Eu.max(16384),running:j().nullable()}).strict();N({}).strict(),N({harnesses:M(N({harnessId:Xs,name:Eu.max(128)}).strict()).max(128)}).strict(),N({harnessId:Xs,query:D().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:k().int().nonnegative().safe().optional(),limit:k().int().min(1).max(Tu).optional()}).strict(),N({candidates:M(Ou).max(Tu),total:k().int().nonnegative().safe()}).strict(),N({harnessId:Xs,nativeSessionId:Du}).strict(),N({threadId:Eu.max(1024).pipe(H)}).strict();let ku=D().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Au=Du,ju=Ou;N({}).strict(),N({candidates:M(ju).max(1e3)}).strict(),N({nativeSessionId:Au}).strict(),N({threadId:ku.max(1024).pipe(H)}).strict(),N({threadId:H,lastTurnId:_s}).strict(),N({threadId:H}).strict();let Mu=D().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();N({commands:M(N({id:Mu,invocation:D().min(1).max(128),label:D().trim().min(1).max(128),description:D().trim().min(1).max(512).optional(),localizations:ms.optional(),argumentMode:R([`none`,`text`]),kind:R([`command`,`skill`]).optional()}).strict()),warnings:M(D().min(1)).optional(),source:R([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),N({harnessId:V,cwd:D().min(1).optional()}).strict(),N({threadId:H}).strict(),N({threadId:H,commandId:Mu,turnId:_s.optional(),arguments:us.optional()}).strict(),N({accepted:z(!0),turnId:_s.optional()}).strict();let Nu=z(`2.0`).optional(),Z=xo().optional(),Pu=D().min(1),Fu=F([D(),k().int()]),Iu=N({code:k().int(),message:D(),data:B.optional()}).catchall(B).superRefine(as([`data`]));F([N({jsonrpc:Nu,id:Fu,method:Pu,params:B.optional(),result:Z,error:Z}).catchall(B).superRefine(as([`jsonrpc`,`params`,`result`,`error`])),N({jsonrpc:Nu,id:Z,method:Pu,params:B.optional(),result:Z,error:Z}).catchall(B).superRefine(as([`jsonrpc`,`id`,`params`,`result`,`error`])),N({jsonrpc:Nu,id:Fu,method:Z,params:Z,result:B,error:Z}).catchall(B).superRefine(as([`jsonrpc`,`method`,`params`,`error`])),N({jsonrpc:Nu,id:Fu,method:Z,params:Z,result:Z,error:Iu}).catchall(B).superRefine(as([`jsonrpc`,`method`,`params`,`result`]))]);let Lu=D().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});P({harnessId:V,nativeSessionId:Lu,locator:B.optional(),formatVersion:z(1)}).superRefine(as([`locator`])),P({harnessId:V,nativeSessionId:Lu,nativeTurnKey:Lu,formatVersion:z(1)}),P({harnessId:V,nativeSessionId:Lu,checkpointId:Lu,locator:B.optional(),formatVersion:z(1)}).superRefine(as([`locator`]));let Ru=D().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),zu=R([`npm`,`windows-installer`,`macos-dmg`]),Bu=P({version:Ru,installation:zu,phase:R([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:k().int().nonnegative(),downloadedBytes:k().int().nonnegative().optional(),totalBytes:k().int().positive().optional(),error:D().min(1).max(500).nullable(),serviceStopOutput:D().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});P({});let Vu=D().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`);P({currentVersion:Ru,installation:zu.nullable(),latestVersion:Ru.nullable(),updateAvailable:j(),installationAvailable:j(),releaseNotes:D().min(1).max(2e4).nullable(),releaseNotesUrl:Vu.nullable(),status:Bu.nullable(),error:D().min(1).max(500).nullable()}),P({status:Bu}),P({status:Bu.nullable()}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Hu=R([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);N({runningVersion:D().nullable(),installedVersion:D().nullable(),restartRequired:j(),remote:j(),updateSupported:j(),update:N({phase:Hu,targetVersion:D().nullable(),error:D().nullable()})});let Uu=N({version:D().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();N({hostname:D().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable(),action:R([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:j().optional(),version:D().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),N({state:R([`installed`,`not-installed`])}).strict();let Q=D().min(1).max(1024),Wu={hostId:Q.regex(/^remote-(?:ssh(?:-|:)|control:)/u)},$={...Wu,threadId:Q},Gu=I(`kind`,[P({kind:z(`hosts`)}),P({kind:z(`status`),...$}),P({kind:z(`list`),...Wu,cursor:D().nullable(),archived:j()}),P({kind:z(`read`),...$,page:P({cursor:D().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:R([`asc`,`desc`]).optional(),limit:k().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),P({kind:z(`usage`),...$,epoch:Q}),P({kind:z(`configure`),...$,epoch:Q,modelId:Q.optional(),serviceTier:Fs.optional(),thinkingOptionId:Q.optional(),permissionModeId:Q.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),P({kind:z(`prompt`),...$,epoch:Q,text:D().min(1).max(8e3),requestId:Q.optional()}),P({kind:z(`interrupt`),...$,epoch:Q,turnId:Q}),P({kind:z(`rename`),...$,epoch:Q,name:D().min(1).max(512)}),P({kind:z(`archive`),...$,epoch:Q,archived:j()}),P({kind:z(`respond`),...$,epoch:Q,requestId:F([Q,k().int()]),result:L(D(),yo())})]),Ku=D().min(1).max(1024),qu=N({hostId:Ku,displayName:D().min(1).max(1024),source:R([`codex-managed`,`discovered`]),sshAlias:D().max(1024).nullable(),sshHost:D().min(1).max(1024),sshPort:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable(),autoConnect:j(),connectionAnalyticsId:D().max(1024).optional()}),Ju=P({displayName:D().min(1).max(1024),hostname:D().min(1).max(1024),sshPort:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable()});I(`action`,[P({action:z(`session`),operation:Gu}),P({action:z(`list`)}),P({action:z(`catalog`)}),P({action:z(`read-thread`),hostId:Ku.refine(e=>e!==`local`),input:Nl}),P({action:z(`save`),draft:Ju,previous:qu.nullable()}),P({action:z(`remove`),previous:qu}),P({action:z(`connect`),hostId:Ku,enabled:j()}),P({action:z(`state`),hostId:Ku}),P({action:z(`runtime`),hostId:Ku}),P({action:z(`update`),hostId:Ku.refine(e=>e!==`local`),version:Uu.shape.version})]),F([P({result:B}),P({error:P({code:k().int(),message:D()})})]),P({prompt:D().trim().min(1).max(2e3),cwd:D().max(4096).nullable()}),D().trim().min(1).max(60).nullable();let Yu=D().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),Xu=F([D(),N({en:D()}).catchall(D())]),Zu=N({title:Xu.optional(),description:Xu.optional(),icon:D().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:D().optional()});N({extensions:M(N({id:Yu,name:D().min(1).max(214),version:D().min(1).max(128),format:z(`dsh`),supportedTargets:ko([z(`web`)]),enabledTargets:M(z(`web`)).max(1),source:D().min(1).max(4096),projectUrl:D().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:D(),meta:Zu.optional(),loadError:D().optional()})),loadedIds:M(Yu),safeMode:j(),storeError:D().optional()});let Qu=D().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);N({spec:D().trim().min(1).max(4096),registry:Qu.optional()}).strict(),N({id:Yu,enabled:j()}).strict(),N({id:Yu}).strict(),z(1);function $u(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
123
123
  /* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
124
124
  if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];
125
125
  /* v8 ignore next -- dense-array guard: following is bounded by baseline.length. */
126
- if(e===void 0)continue;let a=i.findIndex(t=>n(t)===n(e));if(a!==-1){o=a;break}}i.splice(o,0,r),a.add(n(r))}return i}let xu={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
127
- `,r:`\r`,t:` `},Su=/[\\\u0000-\u001f]/u;function Cu(e){return e===` `||e===`
128
- `||e===`\r`||e===` `}function wu(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(Su),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++)wu(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=xu[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&&Su.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(Cu(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(Cu(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(Cu(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(Cu(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(Cu(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(Cu(e))return;this.fail();return;
126
+ if(e===void 0)continue;let a=i.findIndex(t=>n(t)===n(e));if(a!==-1){o=a;break}}i.splice(o,0,r),a.add(n(r))}return i}let ed={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
127
+ `,r:`\r`,t:` `},td=/[\\\u0000-\u001f]/u;function nd(e){return e===` `||e===`
128
+ `||e===`\r`||e===` `}function rd(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(td),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++)rd(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=ed[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&&td.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(nd(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(nd(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(nd(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(nd(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(nd(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(nd(e))return;this.fail();return;
129
129
  /* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
130
130
  case`invalid`:return;
131
131
  /* v8 ignore next 2 -- Every scanner mode has a handler above. */
132
- default:Tu(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){Cu(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===`}`||Cu(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 Tu(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function Eu(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 Du(e){return Object.getPrototypeOf(e)===null&&Eu(e,`Object`)}function Ou(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Eu(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&Du(n)}function ku(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&Du(t)}function Au(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function ju(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(!Ou(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(!ku(r))return;let o=Au(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];
132
+ default:id(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){nd(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===`}`||nd(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 id(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function ad(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 od(e){return Object.getPrototypeOf(e)===null&&ad(e,`Object`)}function sd(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!ad(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&od(n)}function cd(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&od(t)}function ld(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function ud(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(!sd(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(!cd(r))return;let o=ld(r);if(o===void 0)return;let s=t?{}:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o.length-1;e>=0;e--){let t=o[e];
133
133
  /* v8 ignore next -- the loop is bounded by the captured key count. */
134
- if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function Mu(e){return ju(e,!0)}function Nu(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
134
+ if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function dd(e){return ud(e,!0)}function fd(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
135
135
  /* v8 ignore next -- the loop condition guarantees one pending task. */
136
136
  if(e===void 0)continue;if(e.kind===`property`){n.push({kind:`visit`,node:e.source[e.key]});continue}let r=e.node;if(typeof r!=`object`||!r||r instanceof AbortSignal||t.has(r))continue;t.add(r),Object.freeze(r);let i=Object.keys(r);for(let e=i.length-1;e>=0;e--){let t=i[e];
137
137
  /* v8 ignore next -- the loop is bounded by the captured key count. */
138
- t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function Pu(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 Fu=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]`))}},Iu=class{rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;anyNotifier=new Fu(()=>{});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 Fu(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},Lu=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 Ru(){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 zu(e){return{kind:`leaf`,entries:e,length:e.length}}function Bu(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Vu(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 Hu(e,t,n,r){let i;return{get entries(){return i??=Vu(e),i},hasMore:t,revision:n,change:r}}var Uu=class{listeners=/* @__PURE__ */ new Set;window=zu([]);snapshot=Hu(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=zu(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Bu(zu(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Bu(this.window,zu(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Vu(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=zu(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Hu(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Wu(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Gu(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Ku(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 qu(e){let t=Mu(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Ju(e){let t=[];for(let n of e){let e=Yu(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 Yu(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`:{Qu(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Zu(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Xu(t,e.length,t.type),t}case`tool-call-chunks`:{Qu(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Zu(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 Xu(t,e.length,t.type),t}case`chunk`:{Qu(t,[`type`,`time`,`chunk`],`chunk`);let e=Gu(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=qu(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Nu({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Xu(e,t,n){if(Gu(e.time0),Ku(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 Zu(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Qu(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 $u=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 Ju(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=ed(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 ed(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function td(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let nd={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},rd={...nd,turnWindow:{...nd.turnWindow,minMessages:200}};var id=class{sessionId;remote;baseSeq=ee(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new $u;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 Uu;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Lu(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Iu,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 Fu(()=>{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=Ru(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}async prompt(e,t,n,r){let i=r??Ru();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;if(this.address===void 0){let r=Wu();a=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))a={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,o=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Wu()},n);a=o.ok?{ok:!0,value:{accepted:!0}}:o}return!a.ok&&a.error.code===`remote/outcome-unknown`&&this.hasObservedPrompt(i)&&(a={ok:!0,value:{accepted:!0}}),a.ok?(this.acceptPrompt(),a):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:a.error,requestId:i},this.notifier.markDirty(),a)}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,...nd})}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,...rd}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=ee(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:this.toolOutputs.values,entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(Al),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(nd),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:td(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=ee(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,Al),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:ee(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:ee(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:od(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=od(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,od(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,ad(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){let n=this.submissionSettlements.get(e);
138
+ t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function pd(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 md=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]`))}},hd=class{rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;anyNotifier=new md(()=>{});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 md(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},gd=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 _d(){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 vd(e){return{kind:`leaf`,entries:e,length:e.length}}function yd(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function bd(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 xd(e,t,n,r){let i;return{get entries(){return i??=bd(e),i},hasMore:t,revision:n,change:r}}var Sd=class{listeners=/* @__PURE__ */ new Set;window=vd([]);snapshot=xd(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=vd(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=yd(vd(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=yd(this.window,vd(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=bd(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=vd(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=xd(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Cd(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function wd(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Td(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 Ed(e){let t=dd(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Dd(e){let t=[];for(let n of e){let e=Od(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 Od(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`:{jd(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Ad(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return kd(t,e.length,t.type),t}case`tool-call-chunks`:{jd(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Ad(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 kd(t,e.length,t.type),t}case`chunk`:{jd(t,[`type`,`time`,`chunk`],`chunk`);let e=wd(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=Ed(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return fd({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function kd(e,t,n){if(wd(e.time0),Td(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 Ad(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function jd(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 Md=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 Dd(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=Nd(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 Nd(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Pd(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Fd={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},Id={...Fd,turnWindow:{...Fd.turnWindow,minMessages:200}};var Ld=class{sessionId;remote;baseSeq=ee(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new Md;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 Sd;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new gd(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new hd,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 md(()=>{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=_d(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}async prompt(e,t,n,r){let i=r??_d();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;if(this.address===void 0){let r=Cd();a=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))a={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,o=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Cd()},n);a=o.ok?{ok:!0,value:{accepted:!0}}:o}return!a.ok&&a.error.code===`remote/outcome-unknown`&&this.hasObservedPrompt(i)&&(a={ok:!0,value:{accepted:!0}}),a.ok?(this.acceptPrompt(),a):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:a.error,requestId:i},this.notifier.markDirty(),a)}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,...Fd})}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,...Id}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=ee(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:this.toolOutputs.values,entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(lu),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Fd),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:Pd(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=ee(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,lu),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:ee(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:ee(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:zd(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=zd(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,zd(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,Rd(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){let n=this.submissionSettlements.get(e);
139
139
  /* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
140
- n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function ad(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function od(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 sd=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 cd(e){return e===-1?-1:p(e)}let ld=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]);var ud=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new sd;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];notifier=new Fu(()=>{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(Al)}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 id(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 Iu;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:cd(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(){return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve()}refreshList(e){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let t=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0;let n=this.summaries,r=[];return this.listMutations=r,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:t,...e?{cursor:e}:{}});if(this.listMutations!==r)return;if(i.ok){let a=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...n.filter(e=>!o.has(e.sessionId)&&(s||!t&&a.has(e.sessionId)))],l=this.listPhase===`pending`?c:bu(n,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of r)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=r.reduce(dd,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===r&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==r)return;this.listState=`error`,this.listError=e}finally{this.listMutations===r&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=fd(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:fd(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=dd(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=cd(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,Al)}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=cd(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:Tu(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(ld);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=Pu(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);return e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e),{items:this.itemsCache,hasMore:!!this.nextCursor,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([e,t])=>[e,{values:t.values(),state:`idle`,error:null,...this.projectionLoads.get(e)}]))}}};function dd(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 fd(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var pd=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},md=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 hd(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 gd(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 _d(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let vd=Object.freeze({referenceCount:0,retainedBy:_d({})});async function yd(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 bd=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]);yd(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()}},xd=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 ud(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}loadSummary(e){return this.manager.loadSummary(e)}loadMore(){return this.manager.loadMore()}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new pd(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 md(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,gd(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:_d({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new bd(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?vd:Object.freeze({referenceCount:r,retainedBy:_d(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??vd}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:vd,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,headRefreshRevision:c,summaryOnlyIds:l}=this.manager.getListSnapshot(),u=[],d={};for(let e of t)u.push(e.sessionId),d[e.sessionId]={id:e.sessionId,displayTitle:hd(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:this.retentionSnapshot(e.sessionId).retainedBy,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=d[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?d[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(d[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(d[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;d[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:u,byId:d,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,headRefreshRevision:c??0,summaryOnlyIds:l??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let Sd=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function Cd(e){let t=e.remote,n=e.get(`connection`),r=new xd(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=Uu,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=pd,n.SessionEventStream=pe,n.SessionForkError=md,n.apply=Cd,n.createScope=_e,n.createSessionControlStream=fe,n.inject=Sd,n.scopeOf=ve,t.exports}});
140
+ n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function Rd(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function zd(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 Bd=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 Vd(e){return e===-1?-1:p(e)}let Hd=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]);var Ud=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new Bd;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];notifier=new md(()=>{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(lu)}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 Ld(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 hd;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:Vd(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(){return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve()}refreshList(e){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let t=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0;let n=this.summaries,r=[];return this.listMutations=r,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:t,...e?{cursor:e}:{}});if(this.listMutations!==r)return;if(i.ok){let a=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...n.filter(e=>!o.has(e.sessionId)&&(s||!t&&a.has(e.sessionId)))],l=this.listPhase===`pending`?c:$u(n,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of r)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=r.reduce(Wd,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===r&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==r)return;this.listState=`error`,this.listError=e}finally{this.listMutations===r&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=Gd(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:Gd(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=Wd(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=Vd(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,lu)}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=Vd(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:id(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(Hd);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=pd(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);return e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e),{items:this.itemsCache,hasMore:!!this.nextCursor,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([e,t])=>[e,{values:t.values(),state:`idle`,error:null,...this.projectionLoads.get(e)}]))}}};function Wd(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 Gd(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var Kd=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},qd=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 Jd(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 Yd(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 Xd(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let Zd=Object.freeze({referenceCount:0,retainedBy:Xd({})});async function Qd(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 $d=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]);Qd(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()}},ef=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 Ud(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}loadSummary(e){return this.manager.loadSummary(e)}loadMore(){return this.manager.loadMore()}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new Kd(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 qd(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,Yd(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:Xd({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new $d(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?Zd:Object.freeze({referenceCount:r,retainedBy:Xd(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??Zd}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:Zd,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,headRefreshRevision:c,summaryOnlyIds:l}=this.manager.getListSnapshot(),u=[],d={};for(let e of t)u.push(e.sessionId),d[e.sessionId]={id:e.sessionId,displayTitle:Jd(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:this.retentionSnapshot(e.sessionId).retainedBy,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=d[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?d[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(d[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(d[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;d[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:u,byId:d,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,headRefreshRevision:c??0,summaryOnlyIds:l??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let tf=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function nf(e){let t=e.remote,n=e.get(`connection`),r=new ef(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=Sd,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=Kd,n.SessionEventStream=pe,n.SessionForkError=qd,n.apply=nf,n.createScope=_e,n.createSessionControlStream=fe,n.inject=tf,n.scopeOf=ve,t.exports}});