@codexhost/cli-win32-arm64 0.26.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.txt +1 -1
  3. package/app/codexhost-distribution.json +1 -1
  4. package/app/console-server.mjs +7669 -2363
  5. package/app/console-web.js +7604 -2343
  6. package/app/desktop-controller.mjs +7259 -2056
  7. package/app/host-runtime.mjs +11012 -5608
  8. package/app/plugins/antigravity/plugin.mjs +7620 -2371
  9. package/app/plugins/claude-code/plugin.mjs +7431 -2217
  10. package/app/plugins/codebuddy/plugin.mjs +7697 -2494
  11. package/app/plugins/codex-usage/plugin.mjs +7242 -2039
  12. package/app/plugins/copilot/plugin.mjs +7404 -2201
  13. package/app/plugins/cursor-cli/plugin.mjs +7583 -2380
  14. package/app/plugins/deepseek-harness/plugin.mjs +7825 -2598
  15. package/app/plugins/devin/plugin.mjs +7407 -2204
  16. package/app/plugins/grok/plugin.mjs +7672 -2469
  17. package/app/plugins/hermes/plugin.mjs +7594 -2247
  18. package/app/plugins/kimi-code/plugin.mjs +7494 -2291
  19. package/app/plugins/kiro-cli/plugin.mjs +7509 -2306
  20. package/app/plugins/omp/plugin.mjs +7540 -2337
  21. package/app/plugins/opencode/plugin.mjs +7954 -2751
  22. package/app/plugins/pi/plugin.mjs +7558 -2355
  23. package/app/plugins/qoder/plugin.mjs +7843 -2601
  24. package/app/plugins/qoder-cn/plugin.mjs +7843 -2601
  25. package/app/plugins/qwen-code/plugin.mjs +7527 -2324
  26. package/app/plugins/workbuddy/plugin.mjs +7705 -2502
  27. package/app/plugins/zcode/plugin.mjs +7371 -2168
  28. package/app/renderer-extension.js +7938 -2663
  29. package/app/web/assets/index-CR4Y8Ndj.css +1 -0
  30. package/app/web/assets/index-Dw-yHAxN.js +196 -0
  31. package/app/web/codexhost-settings.js +97 -88
  32. package/app/web/index.html +2 -2
  33. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +98 -106
  34. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +102 -111
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-attachment/client.js +1 -1
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +107 -116
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +106 -115
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +128 -137
  39. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +94 -103
  40. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +112 -121
  41. package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +102 -111
  42. package/app/web/plugins/deepseek-ai__dsh-typert-registry/client.js +8 -8
  43. package/app/web-modules/node_modules/@deepseek-ai/dsh-client-modules/index.js +2 -2
  44. package/app/web-modules/server.mjs +9130 -4614
  45. package/bin/codexhost.exe +0 -0
  46. package/libexec/codexhost-node-repl.exe +0 -0
  47. package/libexec/codexhost-shell.exe +0 -0
  48. package/libexec/codexhost-shim.exe +0 -0
  49. package/libexec/codexhost-updater.exe +0 -0
  50. package/package.json +1 -1
  51. package/app/web/assets/index-BDWdtbFT.js +0 -203
  52. package/app/web/assets/index-jLAmV7OU.css +0 -1
@@ -1,138 +1,129 @@
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
- `).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 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
- if (${n}.issues.length) {
5
- if (${o} in input) {
6
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
7
- ...iss,
8
- path: iss.path ? [${o}, ...iss.path] : [${o}]
9
- })));
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 m(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 ee=/* @__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(`.`)),te=/* @__PURE__ */ new Set([`system/message`,`developer/message`,`user/message`,`assistant/message`,`tool/result`]);function ne(e){return te.has(e)}function re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ie(e,t){let n=e.data;if(te.has(e.type)&&re(n)){let r=e.type===`user/message`?n:n.message;if(re(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=>re(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(!(!re(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(!re(n))throw Error(`${t} data must be an object`);let e=n.header;if(!re(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(re(r)&&Object.keys(r).length===0)throw Error(`${t} must omit empty adapterDefaults`)}else if(e.type===`tool/result`){if(!re(n))throw Error(`${t} data must be an object`);if(n.error===void 0)return;let e=n.message;if(!re(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(!ne(e.type)){if(!ee.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]}function be(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 xe(e,t=`|`){return e.map(e=>qe(e)).join(t)}function Se(e,t){return typeof t==`bigint`?t.toString():t}var Ce=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function we(e){return new Ce(e)}function Te(e){return e==null}function Ee(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function De(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}let Oe=/* @__PURE__*/ Symbol(`evaluating`);function ke(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Oe)return r===void 0&&(r=Oe,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ae(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function je(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Me(e){return je(e._zod.def)??e._zod.def.shape}function Ne(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Ae(this,t,e),e},enumerable:!0,configurable:!0})}function Pe(e,t,n){t in e?Ae(e,t,n):e[t]=n}function Fe(e,t,n,r){let i=Me(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Ne(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Pe(e,a,r?r(n.value,a):n.value))}}function Ie(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Ne(e,n,()=>t[n]):Pe(e,n,r.value))}}function h(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Le(e){return JSON.stringify(e)}function Re(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}let ze=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Be(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let Ve=/* @__PURE__*/ we(()=>{if(b.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function He(e){if(Be(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Be(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Ue(e){return He(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let We=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function Ge(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ke(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function g(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 qe(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Je(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}let Ye={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Xe={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function Ze(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`);let i={};return Fe(i,e,Qe(e,t)),Ke(e,h(n,{shape:i,checks:[]}))}function Qe(e,t){let n=Me(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function $e(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`);let i=new Set(Qe(e,t)),a={};return Fe(a,e,Reflect.ownKeys(Me(e)).filter(e=>!i.has(e))),Ke(e,h(n,{shape:a,checks:[]}))}function et(e,t){if(!He(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Me(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ke(e,h(e._zod.def,{shape:tt(e,t)}))}function tt(e,t){let n={};return Fe(n,e,Reflect.ownKeys(Me(e))),Ie(n,t),n}function nt(e,t){if(!He(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ke(e,h(e._zod.def,{shape:tt(e,t)}))}function rt(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return Fe(n,e,Reflect.ownKeys(Me(e))),Fe(n,t,Reflect.ownKeys(Me(t))),Ke(e,h(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function it(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(Qe(t,n)):void 0,o={};return Fe(o,t,Reflect.ownKeys(Me(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Ke(t,h(t._zod.def,{shape:o,checks:[]}))}function at(e,t,n){let r=n?new Set(Qe(t,n)):void 0,i={};return Fe(i,t,Reflect.ownKeys(Me(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Ke(t,h(t._zod.def,{shape:i}))}function _(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 ot(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 st(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ct(e){return typeof e==`string`?e:e?.message}function lt(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function ut(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function dt(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:ct(e.inst?._zod.def?.error?.(e))??ct(a?.(e))??ct(t?.error?.(e))??ct(n.customError?.(e))??ct(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}let ft=/[\uD800-\uDBFF]/;function pt(e){let t=e.length;if(!ft.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function mt(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ht(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function gt(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function _t(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):xt(e,n,r.value)}}function vt(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function yt(e,t,n){return vt(e,t,n,!1)}function bt(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return vt(this,n,r(this))},set(e){vt(this,n,e)}})}return t}function xt(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:vt(this,t,n.bind(this))},set(e){vt(this,t,e)}})}function St(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Ct,wt=!1,Tt={configurable:!0,get(){wt=!0}};function v(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Ct!==e._zod?Ct=void 0:(Ct=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Tt);let e=wt;wt=!1;try{let r=n(this);return wt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),wt||=e,r}catch(n){throw delete this[t],wt||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Et(e,t,n,r){let i=St(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function Dt(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var Ot;let kt=/*@__PURE__*/ Object.freeze({status:`aborted`}),At={value:void 0,enumerable:!1},jt=`captureStackTrace`in Error?Error:null;function Mt(e){let t=jt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return jt=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function y(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=/* @__PURE__ */ new Set}a.prototype=i;let o=n,s=o&&/* @__PURE__ */ new WeakSet;function c(n,r){if(!n._zod){At.value=new a(r);try{Object.defineProperty(n,"_zod",At)}finally{At.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),_t(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Mt(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Nt=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Pt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Ot=globalThis).__zod_globalConfig??(Ot.__zod_globalConfig={});let b=globalThis.__zod_globalConfig;function x(e){return e&&Object.assign(b,e),b}function Ft(){let e=this._zod;return e.message??=JSON.stringify(e.def,Se,2),e.message}function It(e){this._zod.message=e}let Lt={get:Ft,set:It,enumerable:!0,configurable:!0},Rt={value:void 0,enumerable:!1},zt=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Bt=(e,t)=>{e.name=`$ZodError`,Rt.value=t,Object.defineProperty(e,"issues",Rt),Rt.value=void 0,Object.defineProperty(e,"message",Lt);let n=Object.getPrototypeOf(e);zt.has(n)||(zt.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Vt=y(`$ZodError`,Bt);y(`$ZodError`,Bt,void 0,{Parent:Error});function Ht(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Ut(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Ht(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Wt(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],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function Gt(e,t){return{callee:t?.callee??e,Err:t?.Err}}let Kt=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Nt;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>dt(e,o,x())));throw ze(n,a?.callee??t),n}return s.value};return t},qt=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>dt(e,o,x())));throw ze(n,a?.callee??t),n}return s.value};return t},Jt=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 Nt;return a.issues.length?Yt(e,a.issues,i):{success:!0,data:a.value}};function Yt(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>dt(e,n,x()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}let Xt=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?Yt(e,a.issues,i):{success:!0,data:a.value}},Zt=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),Qt=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),$t=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Zt)return!0;if(r.definite===!0&&n===void 0)return!1}return en(e,t,n)});function en(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[Qt]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new Nt;return a.issues.length===0}let tn=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},nn=e=>{let t=Kt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Gt(n,a))};return n},rn=e=>{let t=Kt(e),n=(e,r,i,a)=>t(e,r,i,Gt(n,a));return n},an=e=>{let t=qt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Gt(n,a))};return n},on=e=>{let t=qt(e),n=async(e,r,i,a)=>await t(e,r,i,Gt(n,a));return n},sn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Jt(e)(t,n,i)},cn=e=>(t,n,r)=>Jt(e)(t,n,r),ln=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Xt(e)(t,n,i)},un=e=>async(t,n,r)=>Xt(e)(t,n,r),dn=/^[cC][0-9a-z]{6,}$/,fn=/^[0-9a-z]+$/,pn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,mn=/^[0-9a-vA-V]{20}$/,hn=/^[A-Za-z0-9]{27}$/,gn=/^[a-zA-Z0-9_-]{21}$/;function _n(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}let vn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,yn=/^([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})$/,bn=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)$/,xn=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Sn(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}let Cn=/^(?:(?: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])$/,wn=/^(([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}|:))$/,Tn=/^((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])$/,En=/^(([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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Dn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,On=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,kn=/^https?$/,An=/^\+[1-9]\d{6,14}$/,jn=`(?:(?:\\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])))`;function Mn(e){return RegExp(`^${e}$`)}let Nn=/*@__PURE__*/ Mn(jn);function Pn(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}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Fn(e){return RegExp(`^${Pn(e)}$`)}function In(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Pn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Pn({precision:e.precision})}`:n;return RegExp(`^${jn}T(?:${r})$`)}let Ln=/^[\s\S]{0,}$/,Rn=/^-?\d+$/,zn=/^-?\d+(?:\.\d+)?$/,Bn=/^(?:true|false)$/i,Vn=/^null$/i,Hn=/^[^A-Z]*$/,Un=/^[^a-z]*$/,S=/*@__PURE__*/ y(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Wn=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},Gn={number:`number`,bigint:`bigint`,object:`date`},Kn=/*@__PURE__*/ y(`$ZodCheckLessThan`,(e,t)=>{S.init(e,t);let n=Gn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Gn[typeof r.value]??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})}}),qn=/*@__PURE__*/ y(`$ZodCheckGreaterThan`,(e,t)=>{S.init(e,t);let n=Gn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Gn[typeof r.value]??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})}}),Jn=/*@__PURE__*/ y(`$ZodCheckMultipleOf`,(e,t)=>{S.init(e,t),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`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):De(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})}}),Yn=/*@__PURE__*/ y(`$ZodCheckNumberFormat`,(e,t)=>{S.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ye[t.format];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})}}),Xn=/*@__PURE__*/ y(`$ZodCheckMaxLength`,(e,t)=>{var n;S.init(e,t),(n=e._zod.def).when??(n.when=Wn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?pt(r):i)<=t.maximum)return;let a=mt(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Zn=/*@__PURE__*/ y(`$ZodCheckMinLength`,(e,t)=>{var n;S.init(e,t),(n=e._zod.def).when??(n.when=Wn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?pt(r):i)>=t.minimum)return;let a=mt(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Qn=/*@__PURE__*/ y(`$ZodCheckLengthEquals`,(e,t)=>{var n;S.init(e,t),(n=e._zod.def).when??(n.when=Wn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?pt(r):i;if(a===t.length)return;let o=mt(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$n=/*@__PURE__*/ y(`$ZodCheckStringFormat`,(e,t)=>{var n,r;S.init(e,t),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=()=>{})}),er=/*@__PURE__*/ y(`$ZodCheckRegex`,(e,t)=>{$n.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})}}),tr=/*@__PURE__*/ y(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Hn,$n.init(e,t)}),nr=/*@__PURE__*/ y(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Un,$n.init(e,t)}),rr=/*@__PURE__*/ y(`$ZodCheckIncludes`,(e,t)=>{S.init(e,t);let n=Ge(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),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})}}),ir=/*@__PURE__*/ y(`$ZodCheckStartsWith`,(e,t)=>{S.init(e,t);let n=RegExp(`^${Ge(t.prefix)}.*`);t.pattern??=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})}}),ar=/*@__PURE__*/ y(`$ZodCheckEndsWith`,(e,t)=>{S.init(e,t);let n=RegExp(`.*${Ge(t.suffix)}$`);t.pattern??=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})}}),or=/*@__PURE__*/ y(`$ZodCheckOverwrite`,(e,t)=>{S.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var sr=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
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?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
3
+ `)}\n};`)(...Object.values(this.closed))}};let cr={major:4,minor:6,patch:7},C=/*@__PURE__*/ y(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=cr;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=_(t),a;for(let o of n){if(o._zod.def.when){if(ot(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Nt;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(ut(t.issues,n,e),i||=_(t,n))});else{if(t.issues.length===n)continue;ut(t.issues,n,e),i||=_(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(_(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Nt;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Nt;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return yt(this,`~standard`,dr(this))},set"~standard"(e){vt(this,`~standard`,e)}}),lr=(e,t)=>e.issues.length?{issues:e.issues.map(e=>dt(e,t,x()))}:{value:e.value};async function ur(e,t){let n={async:!0};return lr(await e._zod.run({value:t,issues:[]},n),n)}function dr(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return lr(r,n)}catch{}return ur(e,t)},vendor:`zod`,version:1}}let fr=/*@__PURE__*/ y(`$ZodString`,(e,t)=>{C.init(e,t),e._zod.pattern=t.pattern??Ln,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}}),w=/*@__PURE__*/ y(`$ZodStringFormat`,(e,t)=>{$n.init(e,t),fr.init(e,t)}),pr=/*@__PURE__*/ y(`$ZodGUID`,(e,t)=>{t.pattern??=yn,w.init(e,t)}),mr=/*@__PURE__*/ y(`$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??=bn(e)}else t.pattern??=bn();w.init(e,t)}),hr=/*@__PURE__*/ y(`$ZodEmail`,(e,t)=>{t.pattern??=xn,w.init(e,t)});function gr(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function _r(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?gr(e)||2:vr(e,t)}function vr(e,t){if(!t.normalize&&t.protocol?.source===kn.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}let yr=/[\t\n\r]/g;function br(e){return e.replace(yr,``)}function xr(e,t){return t.lastIndex=0,t.test(e.hostname)}function Sr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}let Cr=/*@__PURE__*/ y(`$ZodURL`,(e,t)=>{w.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=_r(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=br(r);return}t.hostname&&!xr(i,t.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&&!Sr(i,t.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:br(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),wr=/*@__PURE__*/ y(`$ZodEmoji`,(e,t)=>{t.pattern??=Sn(),w.init(e,t)}),Tr=/*@__PURE__*/ y(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?gn:_n(t.length),w.init(e,t)}),Er=/*@__PURE__*/ y(`$ZodCUID`,(e,t)=>{t.pattern??=dn,w.init(e,t)}),Dr=/*@__PURE__*/ y(`$ZodCUID2`,(e,t)=>{t.pattern??=fn,w.init(e,t)}),Or=/*@__PURE__*/ y(`$ZodULID`,(e,t)=>{t.pattern??=pn,w.init(e,t)}),kr=/*@__PURE__*/ y(`$ZodXID`,(e,t)=>{t.pattern??=mn,w.init(e,t)}),Ar=/*@__PURE__*/ y(`$ZodKSUID`,(e,t)=>{t.pattern??=hn,w.init(e,t)}),jr=/*@__PURE__*/ y(`$ZodISODateTime`,(e,t)=>{t.pattern??=In(t),w.init(e,t)}),Mr=/*@__PURE__*/ y(`$ZodISODate`,(e,t)=>{t.pattern??=Nn,w.init(e,t)}),Nr=/*@__PURE__*/ y(`$ZodISOTime`,(e,t)=>{t.pattern??=Fn(t),w.init(e,t)}),Pr=/*@__PURE__*/ y(`$ZodISODuration`,(e,t)=>{t.pattern??=vn,w.init(e,t)}),Fr=/*@__PURE__*/ y(`$ZodIPv4`,(e,t)=>{t.pattern??=Cn,w.init(e,t)}),Ir=/^[0-9a-fA-F:.]+$/;function Lr(e){return Ir.test(e)?gr(`http://[${e}]`):!1}let Rr=/*@__PURE__*/ y(`$ZodIPv6`,(e,t)=>{t.pattern??=wn,w.init(e,t),e._zod.check=n=>{Lr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),zr=/*@__PURE__*/ y(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Tn,w.init(e,t)});function Br(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Lr(n)}let Vr=/*@__PURE__*/ y(`$ZodCIDRv6`,(e,t)=>{t.pattern??=En,w.init(e,t),e._zod.check=n=>{Br(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Hr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let Ur=/^[0-9a-zA-Z+/]*={0,2}$/,Wr=/*@__PURE__*/ y(`$ZodBase64`,(e,t)=>{t.pattern??=Ur,w.init(e,t),e._zod.check=n=>{Hr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Gr=/^[A-Za-z0-9_-]*$/;function Kr(e){if(!Gr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Hr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}let qr=/*@__PURE__*/ y(`$ZodBase64URL`,(e,t)=>{t.pattern??=Gr,w.init(e,t),e._zod.check=n=>{Kr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Jr=/*@__PURE__*/ y(`$ZodE164`,(e,t)=>{t.pattern??=An,w.init(e,t)});function Yr(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 Xr=/*@__PURE__*/ y(`$ZodJWT`,(e,t)=>{w.init(e,t),e._zod.check=n=>{Yr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Zr=/*@__PURE__*/ y(`$ZodNumber`,(e,t)=>{C.init(e,t),e._zod.pattern=zn,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:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Qr=/*@__PURE__*/ y(`$ZodNumberFormat`,(e,t)=>{Yn.init(e,t),Zr.init(e,t)}),$r=/*@__PURE__*/ y(`$ZodBoolean`,(e,t)=>{C.init(e,t),e._zod.pattern=Bn,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}}),ei=/*@__PURE__*/ y(`$ZodNull`,(e,t)=>{C.init(e,t),e._zod.pattern=Vn,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}}),ti=/*@__PURE__*/ y(`$ZodUnknown`,(e,t)=>{C.init(e,t),e._zod.parse=e=>e}),ni=/*@__PURE__*/ y(`$ZodNever`,(e,t)=>{C.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function ri(e,t){let n=lt(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of lt(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,ut(n.issues,t,e),n}}return i(n,a)}}let ii=e=>Array.isArray(e)?e.length:-1;function ai(e,t,n){e.issues.length&&t.issues.push(...st(n,e.issues)),t.value[n]=e.value}let oi=/*@__PURE__*/ y(`$ZodArray`,(e,t)=>{C.init(e,t);let n=b.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>ai(t,r,e)));else if(ai(c,r,e),s&&c.issues.length!==0&&_(c))break}return o.length?Promise.all(o).then(()=>r):r},ri(e,ii)});function si(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...st(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}let ci=[];function li(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:ci,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Je(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function ui(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(_(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>si(e,n,i,t,d,f))):si(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}let di=/*@__PURE__*/ y(`$ZodObject`,(e,t)=>{C.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=we(()=>li(t));v(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Ae(n,e,/* @__PURE__ */ new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=Be,o=t.catchall,s,c=b.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(_(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>si(n,t,e,r,a,o))):si(s,t,e,r,a,o)}return o?ui(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),fi=/*@__PURE__*/ y(`$ZodObjectJIT`,(e,t)=>{di.init(e,t);let n=e._zod.parse,r=we(()=>li(t)),i=b.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new sr([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
4
+ let ${e}_ab = false;
5
+ for (let i = 0; i < ${e}.issues.length; i++) {
6
+ const iss = ${e}.issues[i];
7
+ iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
8
+ payload.issues.push(iss);
9
+ if (iss.continue !== true) ${e}_ab = true;
10
10
  }
11
- }
12
-
13
- if (${n}.value === undefined) {
14
- if (${o} in input) {
15
- newResult[${o}] = undefined;
11
+ if (${e}_ab && ctx && ctx.abortEarly) {
12
+ payload.value = newResult;
13
+ return payload;
14
+ }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:Le(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
15
+ const ${n}_present = ${i};
16
+ if (!${n}.issues.length || ${n}_present) {
17
+ if (${n}.issues.length) {${c(n,r)}
18
+ }
19
+
20
+ if (${e}) {
21
+ newResult[${r}] = ${n}.value;
16
22
  }
17
- } else {
18
- newResult[${o}] = ${n}.value;
19
23
  }
20
-
21
- `):c?t.write(`
22
- if (${n}.issues.length) {
23
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
24
- ...iss,
25
- path: iss.path ? [${o}, ...iss.path] : [${o}]
26
- })));
24
+
25
+ `)}else f?(o.write(`
26
+ if (${n}.issues.length) {${c(n,r)}
27
27
  }
28
-
29
- if (${n}.value === undefined) {
30
- if (${o} in input) {
31
- newResult[${o}] = undefined;
32
- }
33
- } else {
34
- newResult[${o}] = ${n}.value;
28
+ `),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
29
+ if (${n}.value !== undefined || ${i}) {
30
+ newResult[${r}] = ${n}.value;
35
31
  }
36
-
37
- `):t.write(`
38
- const ${n}_present = ${o} in input;
39
- if (${n}.issues.length) {
40
- payload.issues = payload.issues.concat(${n}.issues.map(iss => ({
41
- ...iss,
42
- path: iss.path ? [${o}, ...iss.path] : [${o}]
43
- })));
32
+ `)):o.write(`
33
+ const ${n}_present = ${i};
34
+ if (${n}.issues.length) {${c(n,r)}
44
35
  }
45
36
  if (!${n}_present && !${n}.issues.length) {
46
37
  payload.issues.push({
47
38
  code: "invalid_type",
48
39
  expected: "nonoptional",
49
40
  input: undefined,
50
- path: [${o}]
41
+ path: [${r}]
51
42
  });
43
+ if (ctx && ctx.abortEarly) {
44
+ payload.value = newResult;
45
+ return payload;
46
+ }
52
47
  }
53
48
 
54
49
  if (${n}_present) {
55
- if (${n}.value === undefined) {
56
- newResult[${o}] = undefined;
57
- } else {
58
- newResult[${o}] = ${n}.value;
59
- }
50
+ newResult[${r}] = ${n}.value;
60
51
  }
61
52
 
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>
53
+ `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Be,c=!b.jitless,l=c&&Ve.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?ui([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function pi(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));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=>dt(e,r,x())))}),t)}let mi=/*@__PURE__*/ y(`$ZodUnion`,(e,t)=>{C.init(e,t),v(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),v(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),v(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),v(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Ee(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=>pi(t,r,e,i)):pi(o,r,e,i)}});function hi(e){let t=/* @__PURE__ */ new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}let gi=/*@__PURE__*/ y(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,mi.init(e,t);let n=e._zod.parse;v(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||Ae(t,e,/* @__PURE__ */ new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=je(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=we(()=>hi(t));e._zod.parse=(i,a)=>{let o=i.value;if(!Be(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._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()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),_i=/*@__PURE__*/ y(`$ZodIntersection`,(e,t)=>{C.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])=>yi(e,t,n)):yi(e,i,a)}});function vi(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(He(e)&&He(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=vi(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=vi(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 yi(e,t,n){let r=/* @__PURE__ */ new Map,i,a=/* @__PURE__ */ new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=vi(t.value,n.value);if(!c.valid){if(_(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}let bi=/*@__PURE__*/ y(`$ZodTuple`,(e,t)=>{C.init(e,t);let n=t.items,r=b.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=xi(n,`optin`),l=xi(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length),d=t.rest?a?.abortEarly:void 0,f=!1;for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):(u[e]=t,d&&!f&&t.issues.length&&(f=_(t)))}if(t.rest&&!f){let e=n.length-1,r=o.slice(n.length),c=i.issues.length;for(let n of r){if(d&&i.issues.length!==c){if(_(i,c))break;c=i.issues.length}e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>Si(t,i,e))):Si(r,i,e)}}return s.length?Promise.all(s).then(()=>Ci(u,i,n,o,l)):Ci(u,i,n,o,l)}});function xi(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function Si(e,t,n){e.issues.length&&t.issues.push(...st(n,e.issues)),t.value[n]=e.value}function Ci(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...st(a,o.issues))}t.value[a]=o.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 wi=/*@__PURE__*/ y(`$ZodRecord`,(e,t)=>{C.init(e,t);let n=b.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!He(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=/* @__PURE__ */ new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>dt(e,i,x())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...st(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...st(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&zn.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>dt(e,i,x())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...st(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...st(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Ti=/*@__PURE__*/ y(`$ZodEnum`,(e,t)=>{C.init(e,t);let n=be(t.entries),r=new Set(n);e._zod.values=r,v(e,`pattern`,e=>{let t=be(e.def.entries).filter(e=>We.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Ge(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),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}}),Ei=/*@__PURE__*/ y(`$ZodLiteral`,(e,t)=>{C.init(e,t);let n=new Set(t.values);e._zod.values=n,v(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?Ge(e):e?Ge(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),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}}),Di=/*@__PURE__*/ y(`$ZodTransform`,(e,t)=>{C.init(e,t),e._zod.optin=`optional`,b.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Pt(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));if(i instanceof Promise)throw new Nt;return n.value=i,n}});function Oi(e,t){return e.value=t.issues.length?void 0:t.value,e}let ki=/*@__PURE__*/ y(`$ZodOptional`,(e,t)=>{C.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,v(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),v(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Oi(e,t)):Oi(e,r)}return t.innerType._zod.run(e,n)}}),Ai=/*@__PURE__*/ y(`$ZodExactOptional`,(e,t)=>{ki.init(e,t),v(e,`values`,e=>e.def.innerType._zod.values),v(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ji=/*@__PURE__*/ y(`$ZodNullable`,(e,t)=>{C.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin),v(e,`optout`,e=>e.def.innerType._zod.optout),v(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(t.source)}|null)$`):void 0}),v(e,`values`,e=>e.def.innerType._zod.values?/* @__PURE__ */ new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Mi=/*@__PURE__*/ y(`$ZodDefault`,(e,t)=>{C.init(e,t),e._zod.optin=`defaulted`,v(e,`values`,e=>e.def.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=>Ni(e,t)):Ni(r,t)}});function Ni(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let Pi=/*@__PURE__*/ y(`$ZodPrefault`,(e,t)=>{C.init(e,t),e._zod.optin=`defaulted`,v(e,`values`,e=>e.def.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))}),Fi=/*@__PURE__*/ y(`$ZodNonOptional`,(e,t)=>{C.init(e,t),v(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].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=>Ii(t,e)):Ii(i,e)}});function Ii(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Li(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>dt(e,r,x()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}let Ri=/*@__PURE__*/ y(`$ZodCatch`,(e,t)=>{C.init(e,t),v(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),v(e,`optout`,e=>e.def.innerType._zod.optout),v(e,`values`,e=>e.def.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({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Li(e,r,t,n)):Li(e,r,t,n)}}),zi=/*@__PURE__*/ y(`$ZodPipe`,(e,t)=>{C.init(e,t),v(e,`values`,e=>e.def.in._zod.values),v(e,`optin`,e=>e.def.in._zod.optin),v(e,`optout`,e=>e.def.out._zod.optout),v(e,`propValues`,e=>e.def.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=>Bi(e,t.in,n)):Bi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Bi(e,t.out,n)):Bi(r,t.out,n)}});function Bi(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}let Vi=/*@__PURE__*/ y(`$ZodReadonly`,(e,t)=>{C.init(e,t),v(e,`propValues`,e=>e.def.innerType._zod.propValues),v(e,`values`,e=>e.def.innerType._zod.values),v(e,`optin`,e=>e.def.innerType?._zod?.optin),v(e,`optout`,e=>e.def.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(Hi):Hi(r)}});function Hi(e){return e.memo||(e.value=Object.freeze(e.value)),e}let Ui=/*@__PURE__*/ y(`$ZodLazy`,(e,t)=>{C.init(e,t),ke(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),v(e,`pattern`,e=>e.innerType?._zod?.pattern),v(e,`propValues`,e=>e.innerType?._zod?.propValues),v(e,`optin`,e=>e.innerType?._zod?.optin??void 0),v(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Wi=/*@__PURE__*/ y(`$ZodCustom`,(e,t)=>{S.init(e,t),C.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=>Gi(t,n,r,e));Gi(i,n,r,e)}});function Gi(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(gt(e))}}var Ki=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};let qi=`~memo`,Ji=[];function Yi(e){return typeof e==`object`&&!!e}function Xi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let Zi=/*@__PURE__*/ new WeakMap;function Qi(e,t,n){let r=Zi.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,a=e=>{if(i!==2&&e?._zod){let r=Qi(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?Qi(o.value,t,n):0;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=je(c);s(e?o(e,!0):1),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Qi(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),$i(e,i)}function $i(e,t){return t!==1&&Zi.set(e,t===2),t}function ea(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let ta,na=[],ra={alloc(e,t,n){let r=ta;if(!r)return n;ta=void 0;let i={value:n,issues:null};return r.set(t.value,i),na.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&aa(n,e.value))throw new Ki;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Qi(e,/* @__PURE__ */ new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!Yi(l))return t(s,c);let u=c[qi];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[qi]=u);let d;i===c?d=a:(d=ea(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Xi(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;ta=d;let p=na.length,m=t(s,c);ta=void 0;let ee=na.length>p?na.pop():void 0;return m instanceof Promise?m.then(e=>(ee&&(ee.issues=e.issues.length?Xi(e.issues):Ji),e)):(ee&&(ee.issues=m.issues.length?Xi(m.issues):Ji),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function ia(){return ra}function aa(e,t){let n=e[qi]?.backEdges;return n!==void 0&&Yi(t)&&n.has(t)}let oa=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(ht(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${qe(e.values[0])}`:`Invalid option: expected one of ${xe(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${xe(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function sa(){return{localeError:oa()}}var ca,la=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 ua(){return new la}(ca=globalThis).__zod_globalRegistry??(ca.__zod_globalRegistry=ua());let da=globalThis.__zod_globalRegistry;function fa(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
54
+ function pa(e,t){return new e(fa({type:`string`,...g(t)}))}// @__NO_SIDE_EFFECTS__
55
+ function ma(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
56
+ function ha(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
57
+ function ga(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
58
+ function _a(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...g(t)})}// @__NO_SIDE_EFFECTS__
59
+ function va(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...g(t)})}// @__NO_SIDE_EFFECTS__
60
+ function ya(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...g(t)})}// @__NO_SIDE_EFFECTS__
61
+ function ba(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
62
+ function xa(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
63
+ function Sa(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
64
+ function Ca(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
65
+ function wa(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
66
+ function Ta(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
67
+ function Ea(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
68
+ function Da(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
69
+ function Oa(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
70
+ function ka(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
71
+ function Aa(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
72
+ function ja(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
73
+ function Ma(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
74
+ function Na(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
75
+ function Pa(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
76
+ function Fa(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
77
+ function Ia(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...g(t)})}// @__NO_SIDE_EFFECTS__
78
+ function La(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...g(t)})}// @__NO_SIDE_EFFECTS__
79
+ function Ra(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...g(t)})}// @__NO_SIDE_EFFECTS__
80
+ function za(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...g(t)})}// @__NO_SIDE_EFFECTS__
81
+ function Ba(e,t){return new e(fa({type:`number`,checks:[],...g(t)}))}// @__NO_SIDE_EFFECTS__
82
+ function Va(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...g(t)})}// @__NO_SIDE_EFFECTS__
83
+ function Ha(e,t){return new e({type:`boolean`,...g(t)})}// @__NO_SIDE_EFFECTS__
84
+ function Ua(e,t){return new e({type:`null`,...g(t)})}// @__NO_SIDE_EFFECTS__
85
+ function Wa(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
86
+ function Ga(e,t){return new e({type:`never`,...g(t)})}// @__NO_SIDE_EFFECTS__
87
+ function Ka(e,t){return new Kn({check:`less_than`,...g(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
88
+ function qa(e,t){return new Kn({check:`less_than`,...g(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
89
+ function Ja(e,t){return new qn({check:`greater_than`,...g(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
90
+ function Ya(e,t){return new qn({check:`greater_than`,...g(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
91
+ function Xa(e,t){return new Jn({check:`multiple_of`,...g(t),value:e})}// @__NO_SIDE_EFFECTS__
92
+ function Za(e,t){return new Xn({check:`max_length`,...g(t),maximum:e})}// @__NO_SIDE_EFFECTS__
93
+ function Qa(e,t){return new Zn({check:`min_length`,...g(t),minimum:e})}// @__NO_SIDE_EFFECTS__
94
+ function $a(e,t){return new Qn({check:`length_equals`,...g(t),length:e})}// @__NO_SIDE_EFFECTS__
95
+ function eo(e,t){return new er({check:`string_format`,format:`regex`,...g(t),pattern:e})}// @__NO_SIDE_EFFECTS__
96
+ function to(e){return new tr({check:`string_format`,format:`lowercase`,...g(e)})}// @__NO_SIDE_EFFECTS__
97
+ function no(e){return new nr({check:`string_format`,format:`uppercase`,...g(e)})}// @__NO_SIDE_EFFECTS__
98
+ function ro(e,t){return new rr({check:`string_format`,format:`includes`,...g(t),includes:e})}// @__NO_SIDE_EFFECTS__
99
+ function io(e,t){return new ir({check:`string_format`,format:`starts_with`,...g(t),prefix:e})}// @__NO_SIDE_EFFECTS__
100
+ function ao(e,t){return new ar({check:`string_format`,format:`ends_with`,...g(t),suffix:e})}// @__NO_SIDE_EFFECTS__
101
+ function oo(e){return new or({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
102
+ function so(e){return/* @__PURE__ */ oo(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
103
+ function co(){return/* @__PURE__ */ oo(e=>e.trim())}// @__NO_SIDE_EFFECTS__
104
+ function lo(){return/* @__PURE__ */ oo(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
105
+ function uo(){return/* @__PURE__ */ oo(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
106
+ function fo(){return/* @__PURE__ */ oo(e=>Re(e))}// @__NO_SIDE_EFFECTS__
107
+ function po(e,t,n){return new e({type:`array`,element:t,...g(n)})}// @__NO_SIDE_EFFECTS__
108
+ function mo(e,t,n){let r=g(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
109
+ function ho(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}// @__NO_SIDE_EFFECTS__
110
+ function go(e,t){let n=/* @__PURE__ */ _o(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(gt(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(gt(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
111
+ function _o(e,t){let n=new S({check:`custom`,...g(t)});return n._zod.check=e,n}function vo(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ae(e,t,n[t]);return e}function yo(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??da,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function bo(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function T(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,T(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&vo(o.schema,c),t.io===`input`&&E(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function xo(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function So(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${xo(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+xo(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
121
112
 
122
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}}function qi(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Yi(t,`input`,e.processors),output:Yi(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function w(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return w(r.element,n);if(r.type===`set`)return w(r.valueType,n);if(r.type===`lazy`)return w(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`)return w(r.innerType,n);if(r.type===`intersection`)return w(r.left,n)||w(r.right,n);if(r.type===`record`||r.type===`map`)return w(r.keyType,n)||w(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:w(r.in,n)||w(r.out,n);if(r.type===`object`){for(let e in r.shape)if(w(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(w(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(w(e,n))return!0;return!!(r.rest&&w(r.rest,n))}return!1}let Ji=(e,t={})=>n=>{let r=Gi({...n,processors:t});return C(e,r),Ki(r,e),qi(r,e)},Yi=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Gi({...i??{},target:a,io:t,processors:n});return C(e,o),Ki(o,e),qi(o,e)},Xi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Zi=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Xi[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Qi=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(i.multipleOf=c)},$i=(e,t,n,r)=>{n.type=`boolean`},ea=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ta=(e,t,n,r)=>{n.not={}},na=(e,t,n,r)=>{let i=e._zod.def,a=Te(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},ra=(e,t,n,r)=>{let i=e._zod.def,a=[];for(let e of i.values)if(e===void 0){if(t.unrepresentable===`throw`)throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof e==`bigint`){if(t.unrepresentable===`throw`)throw Error(`BigInt literals cannot be represented in JSON Schema`);a.push(Number(e))}else a.push(e);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ia=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},aa=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},oa=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=C(a.element,t,{...r,path:[...r.path,`items`]})},sa=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=C(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=C(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ca=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>C(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},la=(e,t,n,r)=>{let i=e._zod.def,a=C(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=C(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},ua=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>C(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?C(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null;t.target===`draft-2020-12`?(i.prefixItems=c,l&&(i.items=l)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),i.minItems=c.length,l||(i.maxItems=c.length)):(i.items=c,l&&(i.additionalItems=l));let{minimum:u,maximum:d}=e._zod.bag;typeof u==`number`&&(i.minItems=u),typeof d==`number`&&(i.maxItems=d)},da=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=C(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else(t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=C(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=C(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},fa=(e,t,n,r)=>{let i=e._zod.def,a=C(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},pa=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ma=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},ha=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},ga=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},_a=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;C(o,t,r);let s=t.seen.get(e);s.ref=o},va=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ya=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ba=(e,t,n,r)=>{let i=e._zod.innerType;C(i,t,r);let a=t.seen.get(e);a.ref=i},xa=/*@__PURE__*/ h(`ZodISODateTime`,(e,t)=>{Mn.init(e,t),O.init(e,t)});function Sa(e){return/* @__PURE__ */ ui(xa,e)}let Ca=/*@__PURE__*/ h(`ZodISODate`,(e,t)=>{Nn.init(e,t),O.init(e,t)});function wa(e){return/* @__PURE__ */ di(Ca,e)}let Ta=/*@__PURE__*/ h(`ZodISOTime`,(e,t)=>{Pn.init(e,t),O.init(e,t)});function Ea(e){return/* @__PURE__ */ fi(Ta,e)}let Da=/*@__PURE__*/ h(`ZodISODuration`,(e,t)=>{Fn.init(e,t),O.init(e,t)});function Oa(e){return/* @__PURE__ */ pi(Da,e)}let T=/*@__PURE__*/ h(`ZodError`,(e,t)=>{ot.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>lt(e,t)},flatten:{value:t=>ct(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Ee,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Ee,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),ka=/* @__PURE__ */ ut(T),Aa=/* @__PURE__ */ dt(T),ja=/* @__PURE__ */ ft(T),Ma=/* @__PURE__ */ mt(T),Na=/* @__PURE__ */ gt(T),Pa=/* @__PURE__ */ _t(T),Fa=/* @__PURE__ */ vt(T),Ia=/* @__PURE__ */ yt(T),La=/* @__PURE__ */ bt(T),Ra=/* @__PURE__ */ xt(T),za=/* @__PURE__ */ St(T),Ba=/* @__PURE__ */ Ct(T),Va=/* @__PURE__ */ new WeakMap;function Ha(e,t,n){let r=Object.getPrototypeOf(e),i=Va.get(r);if(i||(i=/* @__PURE__ */ new Set,Va.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}let E=/*@__PURE__*/ h(`ZodType`,(e,t)=>(x.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:Yi(e,`input`),output:Yi(e,`output`)}}),e.toJSONSchema=Ji(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(t,n)=>ka(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ja(e,t,n),e.parseAsync=async(t,n)=>Aa(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ma(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Na(e,t,n),e.decode=(t,n)=>Pa(e,t,n),e.encodeAsync=async(t,n)=>Fa(e,t,n),e.decodeAsync=async(t,n)=>Ia(e,t,n),e.safeEncode=(t,n)=>La(e,t,n),e.safeDecode=(t,n)=>Ra(e,t,n),e.safeEncodeAsync=async(t,n)=>za(e,t,n),e.safeDecodeAsync=async(t,n)=>Ba(e,t,n),Ha(e,`ZodType`,{check(...e){let t=this.def;return this.clone(Ne(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ue(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(rs(e,t))},superRefine(e,t){return this.check(is(e,t))},overwrite(e){return this.check(/* @__PURE__ */ Pi(e))},optional(){return Io(this)},exactOptional(){return Ro(this)},nullable(){return Bo(this)},nullish(){return Io(Bo(this))},nonoptional(e){return Ko(this,e)},array(){return M(this)},or(e){return F([this,e])},and(e){return Do(this,e)},transform(e){return Xo(this,Po(e))},default(e){return Ho(this,e)},prefault(e){return Wo(this,e)},catch(e){return Jo(this,e)},pipe(e){return Xo(this,e)},readonly(){return Qo(this)},describe(e){let t=this.clone();return Br.add(t,{description:e}),t},meta(...e){if(e.length===0)return Br.get(this);let t=this.clone();return Br.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,"description",{get(){return Br.get(e)?.description},configurable:!0}),e)),Ua=/*@__PURE__*/ h(`_ZodString`,(e,t)=>{bn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zi(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Ha(e,`_ZodString`,{regex(...e){return this.check(/* @__PURE__ */ Oi(...e))},includes(...e){return this.check(/* @__PURE__ */ ji(...e))},startsWith(...e){return this.check(/* @__PURE__ */ Mi(...e))},endsWith(...e){return this.check(/* @__PURE__ */ Ni(...e))},min(...e){return this.check(/* @__PURE__ */ Ei(...e))},max(...e){return this.check(/* @__PURE__ */ Ti(...e))},length(...e){return this.check(/* @__PURE__ */ Di(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Ei(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ ki(e))},uppercase(e){return this.check(/* @__PURE__ */ Ai(e))},trim(){return this.check(/* @__PURE__ */ Ii())},normalize(...e){return this.check(/* @__PURE__ */ Fi(...e))},toLowerCase(){return this.check(/* @__PURE__ */ Li())},toUpperCase(){return this.check(/* @__PURE__ */ Ri())},slugify(){return this.check(/* @__PURE__ */ zi())}})}),Wa=/*@__PURE__*/ h(`ZodString`,(e,t)=>{bn.init(e,t),Ua.init(e,t),e.email=t=>e.check(/* @__PURE__ */ Hr(Ga,t)),e.url=t=>e.check(/* @__PURE__ */ Jr(Ya,t)),e.jwt=t=>e.check(/* @__PURE__ */ li(fo,t)),e.emoji=t=>e.check(/* @__PURE__ */ Yr(Za,t)),e.guid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.uuid=t=>e.check(/* @__PURE__ */ Wr(qa,t)),e.uuidv4=t=>e.check(/* @__PURE__ */ Gr(qa,t)),e.uuidv6=t=>e.check(/* @__PURE__ */ Kr(qa,t)),e.uuidv7=t=>e.check(/* @__PURE__ */ qr(qa,t)),e.nanoid=t=>e.check(/* @__PURE__ */ Xr(Qa,t)),e.guid=t=>e.check(/* @__PURE__ */ Ur(Ka,t)),e.cuid=t=>e.check(/* @__PURE__ */ Zr($a,t)),e.cuid2=t=>e.check(/* @__PURE__ */ Qr(eo,t)),e.ulid=t=>e.check(/* @__PURE__ */ $r(to,t)),e.base64=t=>e.check(/* @__PURE__ */ oi(co,t)),e.base64url=t=>e.check(/* @__PURE__ */ si(lo,t)),e.xid=t=>e.check(/* @__PURE__ */ ei(no,t)),e.ksuid=t=>e.check(/* @__PURE__ */ ti(ro,t)),e.ipv4=t=>e.check(/* @__PURE__ */ ni(io,t)),e.ipv6=t=>e.check(/* @__PURE__ */ ri(ao,t)),e.cidrv4=t=>e.check(/* @__PURE__ */ ii(oo,t)),e.cidrv6=t=>e.check(/* @__PURE__ */ ai(so,t)),e.e164=t=>e.check(/* @__PURE__ */ ci(uo,t)),e.datetime=t=>e.check(Sa(t)),e.date=t=>e.check(wa(t)),e.time=t=>e.check(Ea(t)),e.duration=t=>e.check(Oa(t))});function D(e){return/* @__PURE__ */ Vr(Wa,e)}let O=/*@__PURE__*/ h(`ZodStringFormat`,(e,t)=>{S.init(e,t),Ua.init(e,t)}),Ga=/*@__PURE__*/ h(`ZodEmail`,(e,t)=>{Cn.init(e,t),O.init(e,t)}),Ka=/*@__PURE__*/ h(`ZodGUID`,(e,t)=>{xn.init(e,t),O.init(e,t)}),qa=/*@__PURE__*/ h(`ZodUUID`,(e,t)=>{Sn.init(e,t),O.init(e,t)});function Ja(e){return/* @__PURE__ */ Wr(qa,e)}let Ya=/*@__PURE__*/ h(`ZodURL`,(e,t)=>{wn.init(e,t),O.init(e,t)});function Xa(e){return/* @__PURE__ */ Jr(Ya,e)}let Za=/*@__PURE__*/ h(`ZodEmoji`,(e,t)=>{Tn.init(e,t),O.init(e,t)}),Qa=/*@__PURE__*/ h(`ZodNanoID`,(e,t)=>{En.init(e,t),O.init(e,t)}),$a=/*@__PURE__*/ h(`ZodCUID`,(e,t)=>{Dn.init(e,t),O.init(e,t)}),eo=/*@__PURE__*/ h(`ZodCUID2`,(e,t)=>{On.init(e,t),O.init(e,t)}),to=/*@__PURE__*/ h(`ZodULID`,(e,t)=>{kn.init(e,t),O.init(e,t)}),no=/*@__PURE__*/ h(`ZodXID`,(e,t)=>{An.init(e,t),O.init(e,t)}),ro=/*@__PURE__*/ h(`ZodKSUID`,(e,t)=>{jn.init(e,t),O.init(e,t)}),io=/*@__PURE__*/ h(`ZodIPv4`,(e,t)=>{In.init(e,t),O.init(e,t)}),ao=/*@__PURE__*/ h(`ZodIPv6`,(e,t)=>{Ln.init(e,t),O.init(e,t)}),oo=/*@__PURE__*/ h(`ZodCIDRv4`,(e,t)=>{Rn.init(e,t),O.init(e,t)}),so=/*@__PURE__*/ h(`ZodCIDRv6`,(e,t)=>{zn.init(e,t),O.init(e,t)}),co=/*@__PURE__*/ h(`ZodBase64`,(e,t)=>{Vn.init(e,t),O.init(e,t)}),lo=/*@__PURE__*/ h(`ZodBase64URL`,(e,t)=>{Un.init(e,t),O.init(e,t)}),uo=/*@__PURE__*/ h(`ZodE164`,(e,t)=>{Wn.init(e,t),O.init(e,t)}),fo=/*@__PURE__*/ h(`ZodJWT`,(e,t)=>{Kn.init(e,t),O.init(e,t)}),po=/*@__PURE__*/ h(`ZodNumber`,(e,t)=>{qn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qi(e,t,n,r),Ha(e,`ZodNumber`,{gt(e,t){return this.check(/* @__PURE__ */ Si(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},min(e,t){return this.check(/* @__PURE__ */ Ci(e,t))},lt(e,t){return this.check(/* @__PURE__ */ bi(e,t))},lte(e,t){return this.check(/* @__PURE__ */ xi(e,t))},max(e,t){return this.check(/* @__PURE__ */ xi(e,t))},int(e){return this.check(A(e))},safe(e){return this.check(A(e))},positive(e){return this.check(/* @__PURE__ */ Si(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Ci(0,e))},negative(e){return this.check(/* @__PURE__ */ bi(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ xi(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ wi(e,t))},step(e,t){return this.check(/* @__PURE__ */ wi(e,t))},finite(){return this}});let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function k(e){return/* @__PURE__ */ mi(po,e)}let mo=/*@__PURE__*/ h(`ZodNumberFormat`,(e,t)=>{Jn.init(e,t),po.init(e,t)});function A(e){return/* @__PURE__ */ hi(mo,e)}let ho=/*@__PURE__*/ h(`ZodBoolean`,(e,t)=>{Yn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$i(e,t,n,r)});function j(e){return/* @__PURE__ */ gi(ho,e)}let go=/*@__PURE__*/ h(`ZodNull`,(e,t)=>{Xn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ea(e,t,n,r)});function _o(e){return/* @__PURE__ */ _i(go,e)}let vo=/*@__PURE__*/ h(`ZodUnknown`,(e,t)=>{Zn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function yo(){return/* @__PURE__ */ vi(vo)}let bo=/*@__PURE__*/ h(`ZodNever`,(e,t)=>{Qn.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ta(e,t,n,r)});function xo(e){return/* @__PURE__ */ yi(bo,e)}let So=/*@__PURE__*/ h(`ZodArray`,(e,t)=>{er.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oa(e,t,n,r),e.element=t.element,Ha(e,`ZodArray`,{min(e,t){return this.check(/* @__PURE__ */ Ei(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Ei(1,e))},max(e,t){return this.check(/* @__PURE__ */ Ti(e,t))},length(e,t){return this.check(/* @__PURE__ */ Di(e,t))},unwrap(){return this.element}})});function M(e,t){return/* @__PURE__ */ Bi(So,e,t)}let Co=/*@__PURE__*/ h(`ZodObject`,(e,t)=>{ar.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sa(e,t,n,r),_(e,`shape`,()=>t.shape),Ha(e,`ZodObject`,{keyof(){return R(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:yo()})},loose(){return this.clone({...this._zod.def,catchall:yo()})},strict(){return this.clone({...this._zod.def,catchall:xo()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Je(this,e)},safeExtend(e){return Ye(this,e)},merge(e){return Xe(this,e)},pick(e){return Ke(this,e)},omit(e){return qe(this,e)},partial(...e){return Ze(Fo,this,e[0])},required(...e){return Qe(Go,this,e[0])}})});function N(e,t){let n={type:`object`,shape:e??{},...v(t)};return new Co(n)}function P(e,t){return new Co({type:`object`,shape:e,catchall:xo(),...v(t)})}let wo=/*@__PURE__*/ h(`ZodUnion`,(e,t)=>{sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ca(e,t,n,r),e.options=t.options});function F(e,t){return new wo({type:`union`,options:e,...v(t)})}let To=/*@__PURE__*/ h(`ZodDiscriminatedUnion`,(e,t)=>{wo.init(e,t),cr.init(e,t)});function I(e,t,n){return new To({type:`union`,options:t,discriminator:e,...v(n)})}let Eo=/*@__PURE__*/ h(`ZodIntersection`,(e,t)=>{lr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>la(e,t,n,r)});function Do(e,t){return new Eo({type:`intersection`,left:e,right:t})}let Oo=/*@__PURE__*/ h(`ZodTuple`,(e,t)=>{fr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ua(e,t,n,r),e.rest=t=>e.clone({...e._zod.def,rest:t})});function ko(e,t,n){let r=t instanceof x;return new Oo({type:`tuple`,items:e,rest:r?t:null,...v(r?n:t)})}let Ao=/*@__PURE__*/ h(`ZodRecord`,(e,t)=>{gr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>da(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function L(e,t,n){return!t||!t._zod?new Ao({type:`record`,keyType:D(),valueType:e,...v(t)}):new Ao({type:`record`,keyType:e,valueType:t,...v(n)})}let jo=/*@__PURE__*/ h(`ZodEnum`,(e,t)=>{_r.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>na(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new jo({...t,checks:[],...v(r),entries:i})}});function R(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new jo({type:`enum`,entries:n,...v(t)})}let Mo=/*@__PURE__*/ h(`ZodLiteral`,(e,t)=>{vr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ra(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function z(e,t){return new Mo({type:`literal`,values:Array.isArray(e)?e:[e],...v(t)})}let No=/*@__PURE__*/ h(`ZodTransform`,(e,t)=>{yr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>aa(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ce(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(it(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(it(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Po(e){return new No({type:`transform`,transform:e})}let Fo=/*@__PURE__*/ h(`ZodOptional`,(e,t)=>{xr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Io(e){return new Fo({type:`optional`,innerType:e})}let Lo=/*@__PURE__*/ h(`ZodExactOptional`,(e,t)=>{Sr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ro(e){return new Lo({type:`optional`,innerType:e})}let zo=/*@__PURE__*/ h(`ZodNullable`,(e,t)=>{Cr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bo(e){return new zo({type:`nullable`,innerType:e})}let Vo=/*@__PURE__*/ h(`ZodDefault`,(e,t)=>{wr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ma(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ho(e,t){return new Vo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Uo=/*@__PURE__*/ h(`ZodPrefault`,(e,t)=>{Er.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ha(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wo(e,t){return new Uo({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Be(t)}})}let Go=/*@__PURE__*/ h(`ZodNonOptional`,(e,t)=>{Dr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ko(e,t){return new Go({type:`nonoptional`,innerType:e,...v(t)})}let qo=/*@__PURE__*/ h(`ZodCatch`,(e,t)=>{kr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ga(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jo(e,t){return new qo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}let Yo=/*@__PURE__*/ h(`ZodPipe`,(e,t)=>{Ar.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_a(e,t,n,r),e.in=t.in,e.out=t.out});function Xo(e,t){return new Yo({type:`pipe`,in:e,out:t})}let Zo=/*@__PURE__*/ h(`ZodReadonly`,(e,t)=>{Mr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>va(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qo(e){return new Zo({type:`readonly`,innerType:e})}let $o=/*@__PURE__*/ h(`ZodLazy`,(e,t)=>{Pr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ba(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function es(e){return new $o({type:`lazy`,getter:e})}let ts=/*@__PURE__*/ h(`ZodCustom`,(e,t)=>{Fr.init(e,t),E.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ia(e,t,n,r)});function ns(e,t){return/* @__PURE__ */ Vi(ts,e??(()=>!0),t)}function rs(e,t={}){return/* @__PURE__ */ Hi(ts,e,t)}function is(e,t){return/* @__PURE__ */ Ui(e,t)}function as(e){return(t,n)=>{for(let r of e)Object.hasOwn(t,r)&&t[r]===void 0&&n.addIssue({code:`custom`,path:[r],message:`Explicit undefined is not valid JSON`})}}let os=F([D(),k(),j(),_o()]);function ss(e){let t=/* @__PURE__ */ new WeakSet,n=[{value:e,leaving:!1}];try{for(;n.length>0;){let e=n.pop();if(!e)break;if(e.leaving)t.delete(e.value);else if(typeof e.value==`object`&&e.value!==null){if(t.has(e.value))return!1;t.add(e.value),n.push({value:e.value,leaving:!0});for(let t of Object.values(e.value))n.push({value:t,leaving:!1})}}}catch{return!1}return!0}let cs=ns(ss,{message:`JSON value must not contain circular references`}),ls=es(()=>F([os,M(ls),L(D(),ls)])),B=cs.pipe(ls);cs.pipe(M(ls));let us=cs.pipe(L(D(),ls)),ds=P({code:D().min(1),message:D().min(1),retryable:j(),diagnostic:D().min(1).optional(),stage:D().min(1).optional(),durationMs:k().int().nonnegative().optional(),stderrTail:D().min(1).optional()}).superRefine(as([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),fs=D().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),ps=e=>D().min(1).max(e).refine(e=>e.trim().length>0),ms=L(fs,N({label:ps(256).optional(),description:ps(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),hs=L(fs,ps(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),gs=D().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),V=gs.brand(),H=gs.brand(),_s=gs.brand();gs.brand(),gs.brand();let vs=D().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),U=vs.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),ys=N({modes:M(N({id:U,label:vs.max(256),description:vs.max(1024).optional(),dangerous:j().optional(),localizations:ms.optional()}).strict()).min(1).max(32),defaultModeId:U}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});N({threadId:H,permissionModeId:U}).strict();let W=k().int().safe().nonnegative(),bs=k().finite().nonnegative(),xs=k().finite().min(0).max(100),Ss=N({version:F([z(3),z(4)]).optional(),requestId:D().min(1),turnId:D().min(1).max(1024),outputTokens:W,startedAtMs:W,completedAtMs:W}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Cs=N({version:F([z(2),z(3),z(4)]).optional(),value:bs,turnId:D().min(1).max(1024),at:W}).strict();N({outputTimings:M(Ss).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Cs.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Cs.extend({value:W}).optional()}).strict();let ws=e=>hs.refine(t=>Object.values(t).every(t=>t.length<=e)),Ts=N({composerIndicators:M(N({kind:z(`countdown`),id:D().min(1).max(64),expiresAtUnix:W,label:ws(256).optional(),tooltip:ws(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:W.optional(),cachedInputTokens:W.optional(),cacheWriteInputTokens:W.optional(),outputTokens:W.optional(),outputTokensPerSecond:bs.optional(),sessionOutputTokensPerSecond:bs.optional(),apiOutputTokensPerSecond:bs.optional(),reasoningOutputTokens:W.optional(),totalTokens:W.optional(),totalCostUsd:bs.optional(),totalCredits:bs.optional(),contextUsagePercent:bs.optional(),cacheHitRatePercent:xs.optional(),contextWindowTokens:W.optional(),contextUsedTokens:W.optional(),planFiveHourUsedPercent:xs.optional(),planFiveHourResetsAtUnix:W.optional(),planSevenDayUsedPercent:xs.optional(),planSevenDayResetsAtUnix:W.optional(),sessionCacheHitRatePercent:xs.optional(),timeToFirstOutputMs:W.optional(),latestRequestTimeToFirstOutputMs:W.optional(),costSource:R([`publicPrice`,`native`]).optional(),unpricedModels:M(D().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),Es=k().finite().min(0).max(100),Ds=R([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),Os=N({id:D().min(1).max(256),label:D().min(1).max(256),localizations:ms.optional()}).strict(),ks=N({product:D().min(1),periodType:Ds.optional(),scope:Os.optional(),localizations:ms.optional(),used:k().finite().nonnegative().optional(),limit:k().finite().nonnegative().optional(),unit:D().min(1).max(32).optional(),usagePercent:Es,resetsAt:D().min(1).optional()}).strict(),As=N({availableCount:k().int().safe().positive(),nextExpiresAt:D().min(1).optional(),expiresAt:M(D().min(1)).min(1).max(32).optional()}).strict(),js=N({used:k().finite().nonnegative().optional(),limit:k().finite().nonnegative().optional(),unit:D().min(1).max(32).optional(),label:D().min(1).optional(),scope:Os.optional(),localizations:ms.optional(),usedPercent:Es,resetsAt:D().min(1).optional(),periodType:Ds,productUsage:M(ks).min(1).optional(),resetCredits:As.optional()}).strict(),Ms=N({amount:k().finite().nonnegative(),currency:D().trim().min(1).max(8),label:D().trim().min(1).max(128).optional()}).strict();N({threadId:H,refresh:z(`exact`).optional()}).strict(),N({threadId:H,usage:Ts.nullable(),accountCredits:js.optional(),accountBalance:Ms.optional(),accountCreditsSupported:j().optional()}).strict();let Ns=D().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ps=D().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Fs=R([`priority`,`ultrafast`]),G=N({id:Ps,serviceTier:Fs.optional()}).strict();function Is(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let K=Ns.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Ls=Ns.max(256),Rs=N({id:K,label:Ns.max(256)}).strict(),zs=N({ref:G,label:Ns.max(256),resolvedModelLabel:Ls.optional(),fastModel:G.optional(),supportedThinkingOptionIds:M(K).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function Bs(e,t){if(t)return e?.models.find(e=>Is(e.ref,t)||Is(e.fastModel,t))}let Vs=M(Rs).superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Thinking option IDs must be unique`,path:[r,`id`]}),n.add(i.id)}),Hs=N({models:M(zs),defaultModel:G.optional(),thinkingOptions:Vs,defaultThinkingOptionId:K.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>Is(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>Is(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!Bs(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),Us=N({fork:j(),forkAcrossCwd:j(),rollbackLastTurn:j()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Ws=R([`live`,`atCreate`]),Gs=N({configuration:N({selectModel:j(),selectThinkingOption:j(),selectPermissionMode:j(),permissionModeScope:Ws.default(`live`)}).strict(),history:Us,subagents:N({observe:j(),readTranscript:j()}).strict().optional(),autonomousTurns:N({observe:j()}).strict().optional(),steer:j().optional(),persistentPlan:j().optional()}).strict();N({effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),availableThinkingOptions:Vs.optional(),effectivePermissionModeId:U.optional()}).strict().superRefine((e,t)=>{e.effectiveThinkingOptionId&&e.availableThinkingOptions&&!e.availableThinkingOptions.some(({id:t})=>t===e.effectiveThinkingOptionId)&&t.addIssue({code:`custom`,message:`Effective Thinking option must be currently available`,path:[`effectiveThinkingOptionId`]})});let Ks=N({open:z(!0)}).strict();F([N({status:z(`ready`),catalog:Hs,permissionModes:ys.optional(),capabilities:Gs,webUi:Ks.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),N({status:R([`notInstalled`,`unavailable`,`error`]),error:ds}).strict()]),N({harnessId:V,cwd:Ns.max(16384).optional(),refresh:j().optional(),purpose:z(`availability`).optional(),credentialAccess:R([`allow`,`retry`]).optional()}).strict(),N({harnessId:V}).strict(),N({}).strict(),N({threadId:H,model:G}).strict(),N({threadId:H,thinkingOptionId:K}).strict(),N({threadId:H,includeReferenceCapability:j().optional()}).strict(),I(`owner`,[N({owner:z(`codex`),locked:j(),effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),effectivePermissionModeId:U.optional(),history:Us.optional(),supportsThreadReferences:z(!0).optional()}).strict(),N({owner:z(`external`),harnessId:Ns.max(256),transportModelId:Ns.max(8192),effectiveModel:G.optional(),resolvedModelLabel:Ls.optional(),effectiveThinkingOptionId:K.optional(),availableThinkingOptions:Vs.optional(),effectivePermissionModeId:U.optional(),catalog:Hs.optional(),history:Us,usage:Ts.optional(),locked:z(!0)}).strict()]),N({threadIds:M(H).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let qs=I(`owner`,[N({threadId:H,owner:z(`codex`)}).strict(),N({threadId:H,owner:z(`external`),harnessId:D().max(256).pipe(V)}).strict()]);N({threads:M(qs).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),N({threadId:H,text:D().optional()}).strict(),N({kind:z(`application`),value:D().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),xe}}).pipe(N({expectedTurnId:_s,clientUserMessageId:D().min(1),delivery:R([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),R([`activeTurn`,`newTurn`]),N({delivery:R([`official`,`activeTurn`,`newTurn`])}).strict();let Js=D().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),Ys=Js.pipe(V),Xs=Ys.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Zs=D().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),Qs=Xa().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),$s=N({en:D().max(4096),"zh-CN":D().max(4096).optional()}).strict(),ec=N({commands:M(N({terminal:D().max(256),command:D().max(4096)}).strict()).max(8),before:$s.optional(),after:$s.optional(),downloads:M(N({label:D().max(128),url:Qs}).strict()).max(8).optional()}).strict(),tc={id:Ys,name:D().trim().min(1).max(128),version:D().min(1).max(128),kind:z(`usage`).optional(),iconStyle:N({vector:N({viewBox:D().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:D().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:M(N({d:D().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:R([`evenodd`,`nonzero`]).optional(),fill:D().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:D().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:k().min(0).max(50).optional(),paddingRatio:k().min(0).max(.25).optional()}).strict().optional(),installation:ec.optional(),notice:$s.optional(),launchCommand:z(!0).optional(),links:N({website:Qs.optional(),documentation:Qs.optional(),installation:Qs.optional()}).strict().optional()};N({manifestVersion:z(1),...tc,adapterApiVersion:k().int().positive(),entry:Zs,icon:Zs.optional()}).strict();let nc=D().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),rc=N({...tc,icon:nc.optional()}).strict();N({}).strict(),N({plugins:M(rc.extend({id:Xs})).max(128)}).strict(),N({version:z(1),enabled:M(Ys).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let ic=Js,ac=R([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),oc=R([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),sc=D().trim().min(1).max(128);function cc(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let lc=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),uc=Zs.refine(e=>cc(e)!==void 0&&lc(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),dc=D().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Xa({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function fc(e){return P({en:e,"zh-CN":e})}let pc=fc(D().trim().min(1)),mc=M(oc).max(oc.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),hc=M(ac).max(ac.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),gc={key:D().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:pc,description:pc.optional()},_c={...gc,step:k().positive().optional(),default:k().optional()},vc=P({value:D(),label:pc}),yc=I(`type`,[P({...gc,type:z(`boolean`),default:j().optional()}),P({...gc,type:z(`string`),placeholder:pc.optional(),default:D().optional()}),P({..._c,type:z(`number`),min:k().optional(),max:k().optional()}),P({..._c,type:z(`range`),min:k(),max:k()}),P({...gc,type:z(`select`),options:M(vc).min(1),default:D().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),bc=N({manifestVersion:A().positive(),id:ic,name:F([sc,fc(sc)]),version:D().min(1).max(128),desktopApi:A().positive()}).passthrough().extend({manifestVersion:z(1),desktopApi:z(1),description:P({en:D().max(4096),"zh-CN":D().max(4096).optional()}).optional(),author:D().trim().min(1).max(128).optional(),repository:dc.optional(),details:P({en:D().max(16384),"zh-CN":D().max(16384).optional()}).optional(),icon:uc.optional(),screenshots:M(uc).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:P({script:Zs,style:Zs.optional()}).optional(),backend:P({script:Zs.refine(lc)}).optional(),slots:hc.default(()=>[]),settingsSchema:M(yc).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:mc.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),xc=D().regex(/^[a-f0-9]{64}$/u),Sc=P({state:R([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:xc.optional(),error:D().optional(),conflictWith:ic.optional()});P({controllerPid:A().positive(),targetId:D().nullable(),updatedAt:Sa(),handledReloadToken:Ja().optional(),extensions:L(D(),Sc),surfaces:L(D(),Sc).optional()});let Cc=R([`official`,`community`]);function wc(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Tc=dc.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||wc(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),Ec=P({id:ic,version:D().trim().min(1).max(128),name:pc.extend({en:sc,"zh-CN":sc}),description:fc(D().trim().min(1).max(4096)),details:fc(D().trim().min(1).max(16384)).optional(),author:D().trim().min(1).max(128),repository:dc,stars:k().int().min(0).optional(),downloads:k().int().min(0).optional(),categories:mc.optional(),trustTier:Cc.default(`community`),icon:dc.optional(),screenshots:M(dc).max(4).optional(),downloadUrl:Tc,sha256:xc,slots:hc.optional(),publishedAt:D().optional(),updatedAt:D().optional(),minCodexHostVersion:D().optional()});P({schemaVersion:z(1),generatedAt:D(),extensions:M(Ec).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Dc=D().trim().min(1).max(128),Oc=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,kc=ic.refine(e=>!Oc.test(e),`Reserved extension ID`),Ac=R([`desktop`,`web`]),jc=xc,Mc=Ja(),Nc=Zs.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Oc.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),Pc=bc.shape,Fc=(e,t=0)=>P({en:D().trim().min(t).max(e),"zh-CN":D().trim().min(t).max(e)}),Ic=e=>Nc.refine(t=>t.endsWith(e),`Expected a ${e} file`),Lc=Ic(`.mjs`),Rc=Ic(`.css`).optional(),zc=e=>e.normalize(`NFC`).toLowerCase(),Bc=P({manifestVersion:z(2),id:kc,name:Fc(128,1),version:D().trim().min(1).max(128),description:Fc(4096),details:Fc(16384).optional(),author:Pc.author,repository:Pc.repository,icon:Pc.icon.refine(e=>e===void 0||Nc.safeParse(e).success),screenshots:Pc.screenshots.refine(e=>e===void 0||e.every(e=>Nc.safeParse(e).success)),categories:Pc.categories,settingsSchema:Pc.settingsSchema,slots:Pc.slots.removeDefault().optional(),page:P({apiVersion:z(1),entry:Lc,style:Rc,title:Fc(128,1).optional()}).optional(),widget:P({apiVersion:z(1),entry:Lc,style:Rc}).optional(),desktop:P({apiVersion:z(1),script:Ic(`.js`),style:Rc}).optional(),web:P({apiVersion:z(1),entry:Lc.optional(),style:Rc}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:P({apiVersion:z(1),entry:Lc}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||zc(e)!==zc(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Vc({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let Hc=Dc,q=A().nonnegative(),Uc=P({revision:q,enabled:M(kc).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)}),{downloadUrl:Wc,...Gc}=Ec.shape,Kc=N({...Gc,id:kc,format:z(`codexhost`),targets:M(Ac).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:P({page:A().positive().optional(),widget:A().positive().optional(),desktop:A().positive().optional(),web:A().positive().optional(),backend:A().positive().optional()}),downloadUrl:Wc.refine(e=>e.startsWith(`https://`),`Expected HTTPS`)}).refine(({targets:e,apis:t})=>{let n=Vc({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);N({schemaVersion:z(2),generatedAt:D().min(1),extensions:M(Kc).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:dc,fetchedAt:Sa(),cached:j()});let qc={id:kc},Jc={...qc,activationId:Mc,digest:jc},Yc={...qc,activationId:Jc.activationId.optional()},Xc=D().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),Zc=D().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function Qc(e){return D().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let $c=P({type:z(`github`),repository:D().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Zc.optional(),tag:Zc.optional(),asset:D().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Nc.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),el=F([P({type:z(`catalog`),...qc}),$c,P({type:z(`zip`),base64:Qc(67108864).min(4)}),P({type:z(`zip`),localZipPath:Xc}),P({type:z(`localDir`),localDir:Xc})]),tl=I(`type`,[P({type:z(`catalog`),...qc}),$c,P({type:z(`zip`)}),P({type:z(`localDir`)})]),nl=P({...Jc,manifest:Bc,installedAt:Sa(),source:tl.optional()}),rl=e=>D().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),il={desktopConflictWith:kc.optional()},al=R([`none`,`inactive`,`starting`,`running`,`failed`]),ol=I(`state`,[nl.extend({state:z(`valid`),enabled:j(),...il,iconDataUrl:rl(131072).optional(),screenshotDataUrls:M(rl(524288)).max(4).optional(),backendState:al.optional(),backendError:D().optional()}),P({state:R([`invalid`,`incompatible`]),id:D().min(1),enabled:j(),error:D()})]);P({revision:q,configuration:Uc,diagnostics:M(D()),extensions:M(ol)}),P({revision:q,extensions:M(nl.extend({...il,settingsRevision:q})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`},sl=Object.freeze(Object.values(J));new Set(sl),P({});let cl={expectedRevision:q};P({...qc,...cl}),nl.extend({replaced:j()}),I(`state`,[P({state:z(`saved`),configuration:Uc}),P({state:z(`revision-conflict`),revision:q})]),P({...Yc,digest:Jc.digest.optional(),path:Nc}),P({mimeType:D().min(1),base64:Qc(16777216),digest:Jc.digest}),P({settingsRevision:q,values:us}),J.list,J.snapshot,J.catalog,P({forceRefresh:j().optional()}),J.install,P({source:el}),J.update,P({...qc,expectedDigest:Jc.digest,expectedActivationId:Jc.activationId.optional(),source:el.optional()}),J.enable,J.disable,J.uninstall,P({...qc,removeData:j().optional(),expectedDigest:Jc.digest.optional()}),P({...qc,removed:j()}),J.recover,P({expectedRevision:cl.expectedRevision.optional()}),J.asset,J.settingsGet,P(Yc),J.settingsSet,P({...Yc,expectedSettingsRevision:q,values:us}),J.backendInvoke,P({...Yc,method:Hc,params:B.optional()}),P({result:B}),N({threadId:H}).strict(),N({confirmed:j()}).strict(),[...sl],N({sections:M(N({id:D().min(1),name:D().min(1),threads:M(us)}).strict())}).strict(),N({threadId:D().min(1).max(1024),sectionId:D().min(1).max(1024).nullable()}).strict(),N({threadIds:M(D().min(1))}).strict(),N({threadId:D().min(1).max(1024),pinned:j()}).strict(),N({}).strict(),N({parents:L(D().min(1),D().min(1))}).strict(),N({prompt:D().max(16384).optional()}).strict(),N({projects:M(N({id:D(),name:D(),rootPaths:M(D())})),assignments:L(D(),D()),projectless:M(D()),pinned:M(D()),sectionProjects:L(D(),M(D())).optional()});let ll=L(D(),yo()),ul=N({epoch:D().uuid(),sequence:k().int().nonnegative()});I(`type`,[N({type:z(`skills-changed`),cursor:ul,cwd:D().optional()}),N({type:z(`harness-inspection-changed`),cursor:ul,harnessId:D().min(1)}),N({type:z(`display-settings-changed`),cursor:ul}),N({type:z(`preferences-changed`),cursor:ul,revision:k().int().nonnegative()}),N({type:z(`extensions-changed`),cursor:ul,revision:q}),N({type:z(`hello`),version:z(1),cursor:ul,reset:j()}),N({type:z(`changed`),cursor:ul,threadId:D().min(1),method:D().min(1)})]);let dl=I(`type`,[N({type:z(`text`),id:D(),prompt:D(),secret:j().optional(),optional:j().optional()}),N({type:z(`choice`),id:D(),prompt:D(),multiple:j(),allowOther:j(),optional:j().optional(),options:M(N({value:D(),label:D(),description:D().optional()}))})]),fl=I(`type`,[N({type:z(`approval`),title:D(),description:D().optional(),subject:yo().optional(),actions:M(N({id:D(),label:D(),effect:D()}))}),N({type:z(`question`),title:D().optional(),questions:M(dl)})]),pl=N({requestId:F([D(),k().int()]),threadId:D(),kind:R([`approval`,`question`]),interaction:fl,request:ll}),ml=N({id:D().min(1),clientUserMessageId:D().min(1),input:M(ll),presentationInput:M(ll).nullable().optional()}).passthrough();N({fields:M(N({path:M(F([D(),k().int().nonnegative()])),originalLength:k().int().nonnegative()}))});let hl=N({id:D().min(1),status:D().min(1),codexhostTurnOutcome:N({status:z(`unknown`),reason:D()}).optional(),items:M(N({id:D().min(1),type:D().min(1)}).passthrough()),codexhostFileOperations:M(N({beforeItemId:D().nullable(),item:N({id:D().min(1),type:D().min(1)}).passthrough()})).optional(),error:N({message:D().optional()}).passthrough().nullable().optional(),fingerprint:D().min(1).optional(),unchanged:z(!0).optional()}).passthrough(),gl=N({id:D().min(1).max(512),fingerprint:D().min(1).max(128)});N({threadId:D().min(1),knownTurns:M(gl).max(64).optional(),truncateToolOutput:j().optional()});let _l=N({harnessId:D().min(1),nativeSessionId:D().min(1)});N({cursor:ul,activeTurnId:D().min(1).nullable().optional(),command:N({name:D().min(1),turn:hl,subsequentTurnId:D().min(1).optional()}).optional(),thread:N({id:D().min(1),cwd:D(),modelProvider:D().min(1),createdAt:k(),updatedAt:k(),status:N({type:D()}).passthrough(),name:D().nullable().optional(),preview:D().optional(),codexhostImportSource:_l.optional(),turns:M(hl).length(0)}).passthrough(),turnsPage:N({data:M(hl).max(5),nextCursor:D().nullable()}),configuration:N({native:N({model:D().min(1).max(1024).optional(),reasoningEffort:D().min(1).max(128).optional()}).optional(),effectiveModel:G.optional(),effectiveThinkingOptionId:K.optional(),effectivePermissionModeId:U.optional()}),queue:N({items:M(ml),pausedReason:R([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:M(pl)}),N({version:z(1),owner:z(`service`).optional(),pid:k().int().positive(),port:k().int().min(1).max(65535),token:D().regex(/^[0-9a-f]{64}$/u),startedAt:k(),epoch:D().uuid()}),N({epoch:D().uuid(),threadId:D().min(1),requestId:F([D(),k().int()]),result:ll}),N({includeArchived:j().optional(),officialCursor:N({live:D().nullable(),archived:D().nullable().optional()}).strict().optional(),scope:N({cwd:D().min(1).max(4096),excludeCwds:M(D().min(1).max(4096)).max(1024)}).strict().optional()}).strict(),N({threads:M(us),ownership:M(qs),archivedThreadIds:M(H),officialCursor:N({live:D().nullable(),archived:D().nullable().optional()}).strict().optional()}).strict();let vl=R([`running`,`waiting`,`idle`,`unknown`]),yl=P({harnessId:V,title:D().optional(),status:vl,archived:j()}),bl=P({revision:A().nonnegative(),parents:L(H,H),nodes:L(H,yl),truncated:j()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,nodes:t})=>Object.entries(e).every(([e,n])=>Object.hasOwn(t,e)&&Object.hasOwn(t,n)),`Missing Thread tree node`),xl=D().min(1).max(128);P({});let Sl=P({subscriptionId:xl});P({}),Sl.extend({snapshot:bl});let Cl=D().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);N({available:j()}).strict(),N({path:D().min(1),mimeType:Cl}).strict();let wl=R([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);I(`ok`,[N({ok:z(!0),text:D()}).strict(),N({ok:z(!1),error:N({code:wl}).strict()}).strict()]),N({threadId:H.optional(),cwd:D().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Tl=N({name:D().min(1).regex(/^[^\s[\]]+$/u),description:D().optional(),path:D().min(1),scope:R([`project`,`global`]),source:D().min(1)}).strict();N({revision:k().int().nonnegative(),complete:j(),skills:M(Tl),warnings:M(D()).optional()}).strict(),N({cwd:D().min(1).optional()}).strict();let El=N({kind:R([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:D().min(1)}).strict(),Dl=I(`status`,[N({status:z(`not-installed`)}),N({status:z(`not-running`)}),N({status:z(`not-logged-in`)}),N({status:z(`https-disabled`)}),N({status:z(`not-serving`),command:D()}),N({status:z(`occupied`),target:D()}),N({status:z(`serving`),url:D(),funnel:j()}),N({status:z(`error`),message:D()})]);N({state:Dl,error:D().optional()}).strict();let Ol=I(`status`,[N({status:z(`on`)}),N({status:z(`off`)}),N({status:z(`invalid`),reason:D()})]),kl=N({lan:j(),autostart:Ol}).strict(),Al=N({expiresAt:D().optional(),issuing:j(),failure:N({detail:D().optional(),retryAt:D(),paused:j()}).optional()}),jl=I(`status`,[N({status:z(`off`),reason:R([`invite`,`name-taken`,`banned`]).optional()}),N({status:z(`connecting`),reason:R([`full`,`unreachable`]).optional()}),N({status:z(`connected`),url:D(),certificate:Al}),N({status:z(`missing-certificate`),url:D(),certificate:Al}),N({status:z(`stopped`),reason:R([`replaced`,`rejected`,`unsupported-version`])})]);D().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),D().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let Ml=R([`official`,`self-hosted`]);N({secret:D().min(1),lastUsedAt:k().nullable(),networkUrls:M(El),directCandidates:M(El).optional(),tailscale:Dl,background:kl.optional(),relay:N({state:jl,enabled:j(),kind:Ml,officialHost:D(),customHost:D().optional(),officialHostname:D().optional(),customHostname:D().optional(),quotaUntil:D().optional()}).strict().optional()}).strict();let Nl=P({threadId:D().min(1).max(1024),view:R([`result`,`messages`]),from:k().int().min(1).max(2**53-1).optional(),to:k().int().min(1).max(2**53-1).optional()}),Pl=N({id:D().min(1).max(256),harnessId:D().min(1),label:D().min(1).max(512),provider:R([`openai-codex`,`xai`])}).strict(),Fl=D().regex(/^[a-z][a-z0-9-]{0,47}$/),Il=N({name:Fl,source:Pl,importedAt:D()}).strict(),Ll=I(`action`,[N({action:z(`list`)}).strict(),N({action:z(`import`),sourceId:D().min(1).max(256),name:Fl,confirmed:z(!0)}).strict(),N({action:z(`reimport`),sourceId:D().min(1).max(256),name:Fl,confirmed:z(!0)}).strict(),N({action:z(`remove`),name:Fl,confirmed:z(!0)}).strict()]),Rl=N({provider:D().min(1).max(128),type:R([`oauth`,`api_key`,`unknown`]),label:D().min(1).max(512).optional(),vendor:R([`openai-codex`,`xai`]).optional()}).strict();N({sources:M(Pl),targets:M(N({harnessId:D(),providers:M(R([`openai-codex`,`xai`])),imports:M(Il),others:M(Rl).default([])}).strict())}).strict(),N({targetHarnessId:D().min(1).max(128).optional(),request:Ll}).strict(),N({events:j()});let zl=M(P({agent:D().min(1).max(128),section:R([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);P({entries:zl.nullable()}),P({}),P({entries:zl,initializeOnly:j().optional()});let Bl=P({enabled:j(),timeoutMinutes:k().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let Vl=D().regex(/^external$/u),Hl=V.transform(e=>String(e)),Ul=P({model:G.optional(),thinkingOptionId:K.optional(),permissionModeId:U.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),Wl=P({lastHarness:V.optional(),byHarness:L(Hl,Ul)}),Gl=P({model:G.optional(),thinkingOptionId:K.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Kl=P({byHarness:L(Hl,Gl)}),ql=D().min(1).max(1024),Jl=P({idleRelease:Bl.optional(),favorites:L(Hl,M(ql).max(2048)).default({}),newThread:Wl.optional(),delegation:Kl.optional()});P({scope:Vl,revision:k().int().nonnegative(),values:Jl}),P({scope:Vl.default(`external`)});let Yl=I(`kind`,[P({kind:z(`idleRelease`),value:Bl}),P({kind:z(`favorite`),harnessId:V,modelId:ql,enabled:j()}),P({kind:z(`favorites`),harnessId:V,modelIds:M(ql).max(2048)}),P({kind:z(`newThread`),lastHarness:V.optional(),harnessId:V.optional(),configuration:Ul.optional()}),P({kind:z(`delegation`),harnessId:V,configuration:Gl.nullable()})]);P({scope:Vl.default(`external`),operations:M(Yl).min(1).max(256),initializeOnly:j().optional(),expectedRevision:k().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),P({version:z(1),revision:k().int().nonnegative(),scopes:L(Vl,Jl)});let Xl=k().finite().nonnegative(),Zl=P({input:Xl,output:Xl,cacheRead:Xl.optional(),cacheWrite:Xl.optional(),cacheWrite1h:Xl.optional()}),Ql=D().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);P({path:D(),entries:M(P({key:D(),price:Zl})),error:D().nullable()}),P({}),P({key:Ql,price:Zl.nullable(),previousKey:Ql.optional()}),P({model:Ql});let $l=P({official:j().optional(),canonicalModelId:D().min(1).optional(),provider:D().min(1).max(512),model:D().min(1).max(512),price:Zl});P({price:Zl.nullable(),suggestions:M($l).max(6).optional()});let eu=[`today`,`7d`,`30d`,`90d`,`all`],Y=k().int().min(0).max(2**53-1),tu=D().regex(/^\d{4}-\d{2}-\d{2}$/u),nu=D().min(1).max(128),ru=D().min(1).max(512),iu=D().min(1).max(4096);P({range:R(eu),timeZone:D().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:nu.optional(),model:ru.nullable().optional(),project:iu.nullable().optional(),date:tu.optional()});let au=P({requests:Y,inputTokens:Y,cachedInputTokens:Y,cacheWriteInputTokens:Y,cacheKnownInputTokens:Y,cacheHitCachedInputTokens:Y,cacheHitInputTokens:Y,outputTokens:Y,reasoningOutputTokens:Y,costUsd:k().finite().min(0),unpricedRequests:Y,unmeteredRequests:Y}),ou=au.shape,su=P({harness:nu,sessionId:D().min(1).max(512),project:iu.nullable(),title:D().min(1).max(200).optional(),models:M(ru).max(16),firstAtMs:Y,lastAtMs:Y,...ou});P({range:R(eu),from:tu.nullable(),to:tu,filters:P({harness:nu.nullable(),model:ru.nullable(),unknownModel:j(),project:iu.nullable(),unknownProject:j(),date:tu.nullable()}),reading:P({complete:j(),sources:Y,read:Y}),failures:M(P({harness:nu,message:D().max(2048)})).max(256),options:P({harnesses:M(nu).max(256),models:M(ru.nullable()).max(4096),projects:M(iu.nullable()).max(4096)}),modelLabels:M(P({harness:nu,model:ru,label:ru})).max(4096).optional(),credits:M(P({harness:nu,model:ru.nullable(),credits:k().finite().min(0),reportedRequests:Y,requests:Y})).max(4096).optional(),totals:au,daily:M(P({date:tu,harness:nu,...ou})).max(2e5),hourly:M(P({weekday:k().int().min(0).max(6),hour:k().int().min(0).max(23),...ou})).max(168),byHarness:M(P({harness:nu,...ou})).max(256),byModel:M(P({model:ru.nullable(),...ou,harnessPricedRequests:Y})).max(4096),byProject:M(P({project:iu.nullable(),...ou})).max(4096),sessions:M(su).max(100),recentSessions:M(su).max(100).optional()}),N({threadId:H}),N({discarded:j()});let cu=I(`type`,[N({id:D().min(1),type:z(`choice`),prompt:D(),options:M(N({value:D().min(1),label:D(),description:D().optional()})).min(1),multiple:j(),allowOther:j(),optional:j()}),N({id:D().min(1),type:z(`text`),prompt:D(),multiline:j(),secret:z(!1),optional:j(),placeholder:D().optional(),prefill:D().optional()})]),lu=N({interactionId:D().min(1),turnId:D().min(1),title:D().optional(),questions:M(cu).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});P({threadId:D().min(1)}),N({questions:M(lu)}),P({threadId:D().min(1),turnId:D().min(1),interactionId:D().min(1),answers:L(D(),M(D())),cancelled:j().default(!1)}),N({accepted:z(!0)});let uu=`codexhostActiveTurnId`,du=/* @__PURE__ */ new Set([uu,`codexhostTurnChanges`,`codexhostToolOutput`]),fu=N({path:D(),oldText:D().nullable(),newText:D()});N({sessionId:D().min(1),turn:k().int().nonnegative(),path:D().min(1).optional()}),N({diffs:M(fu)}),P({}),P({}),N({reference:N({sessionId:D().min(1),epoch:D().min(1),turn:k().int().nonnegative(),seq:k().int().nonnegative(),callId:D().min(1),part:k().int().nonnegative(),version:D().min(1)}),length:k().int().nonnegative(),bytes:k().int().nonnegative()}),P({title:D().trim().min(1).max(200),type:R([`info`,`warning`,`danger`]),body:D().trim().min(1).max(16384)}),P({}),P({url:D().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status`.split(`.`));let pu=R([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),mu=R([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);P({threadId:D(),title:D(),harnessId:D(),state:pu,reason:mu,inactiveMs:k().nonnegative()}),P({threadId:H,turnId:_s});let hu=N({email:D().trim().min(1).max(320).optional(),label:D().trim().min(1).max(256).optional(),plan:D().trim().min(1).max(128).optional(),credits:js.optional(),balance:Ms.optional()}).strict();function gu(e){return e.refine(e=>{let t=e;return t.credits!==void 0||t.balance!==void 0},{message:`Account must report either credits or a balance`})}let _u=gu(hu),vu={harnessId:V,harnessName:D().trim().min(1).max(128)},yu=N(vu).strict();N({}).strict(),N({sources:M(yu).max(128)}).strict(),N({harnessId:V,refresh:j().optional()}).strict(),N({...vu,account:_u.nullable(),accounts:M(_u).max(8).optional()}).strict(),N({refresh:j().optional()}).strict(),N({accounts:M(gu(hu.extend(vu))).max(128)}).strict(),N({harnessId:Xs,model:G.optional(),thinkingOptionId:K.optional(),permissionModeId:U.optional(),prewarm:z(!0).optional()}).strict();let bu=D().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);N({harnessId:Xs}).strict().extend({path:bu.nullable()}),N({path:bu.nullable(),restartRequired:j()}).strict(),N({harnessId:V,action:R([`check`,`update`,`install`]),confirmedVersion:D().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let xu=N({currentVersion:D().min(1).max(128),latestVersion:D().min(1).max(128),updateAvailable:j(),canUpdate:j(),latestVerifiedVersion:D().min(1).max(128).optional(),confirmationRequired:z(!0).optional(),versionKind:R([`cli`,`application`]).optional(),manualUpdateUrl:Xa().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:D().max(2048).optional(),messageCode:D().min(1).max(128).optional(),notice:hs.optional(),latestVersionKind:R([`unknown`,`tracking-branch`]).optional()}).strict();N({taskId:D().uuid()}).strict(),I(`status`,[N({taskId:D().uuid(),status:z(`running`)}).strict(),N({taskId:D().uuid(),status:z(`succeeded`),result:xu}).strict(),N({taskId:D().uuid(),status:z(`failed`),error:N({code:k().int(),message:D().min(1).max(2048)}).strict()}).strict()]);let Su=D().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Cu=D().trim().min(1),wu=R([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),Tu=N({accountId:Su,label:Cu.max(256),email:D().email().max(320).optional(),planType:wu.optional()}).strict(),Eu=R([`ready`,`unavailable`]);N({version:z(2),currentAccountId:Su.nullable(),phase:Eu,revision:k().int().nonnegative(),instanceId:Cu.max(1024).optional(),accounts:M(Tu).max(1)}).strict(),N({accountId:Su,refresh:j().optional()}).strict(),N({accountId:Su,usage:Ts.nullable(),accountCredits:js.optional(),freshness:R([`live`,`cached`]),observedAt:D().datetime().nullable()}).strict();let Du=1e3,Ou=D().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),ku=Ou.max(1024),Au=N({nativeSessionId:ku,title:Ou.max(4096).nullable(),updatedAt:k().int().nonnegative().max(864e13),cwd:Ou.max(16384),running:j().nullable()}).strict();N({}).strict(),N({harnesses:M(N({harnessId:Xs,name:Ou.max(128)}).strict()).max(128)}).strict(),N({harnessId:Xs,query:D().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:k().int().nonnegative().safe().optional(),limit:k().int().min(1).max(Du).optional()}).strict(),N({candidates:M(Au).max(Du),total:k().int().nonnegative().safe()}).strict(),N({harnessId:Xs,nativeSessionId:ku}).strict(),N({threadId:Ou.max(1024).pipe(H)}).strict();let ju=D().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Mu=ku,Nu=Au;N({}).strict(),N({candidates:M(Nu).max(1e3)}).strict(),N({nativeSessionId:Mu}).strict(),N({threadId:ju.max(1024).pipe(H)}).strict(),N({threadId:H,lastTurnId:_s}).strict(),N({threadId:H}).strict();let Pu=D().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();N({commands:M(N({id:Pu,invocation:D().min(1).max(128),label:D().trim().min(1).max(128),description:D().trim().min(1).max(512).optional(),localizations:ms.optional(),argumentMode:R([`none`,`text`]),kind:R([`command`,`skill`]).optional()}).strict()),warnings:M(D().min(1)).optional(),source:R([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),N({harnessId:V,cwd:D().min(1).optional()}).strict(),N({threadId:H}).strict(),N({threadId:H,commandId:Pu,turnId:_s.optional(),arguments:us.optional()}).strict(),N({accepted:z(!0),turnId:_s.optional()}).strict();let Fu=z(`2.0`).optional(),X=xo().optional(),Iu=D().min(1),Lu=F([D(),k().int()]),Ru=N({code:k().int(),message:D(),data:B.optional()}).catchall(B).superRefine(as([`data`]));F([N({jsonrpc:Fu,id:Lu,method:Iu,params:B.optional(),result:X,error:X}).catchall(B).superRefine(as([`jsonrpc`,`params`,`result`,`error`])),N({jsonrpc:Fu,id:X,method:Iu,params:B.optional(),result:X,error:X}).catchall(B).superRefine(as([`jsonrpc`,`id`,`params`,`result`,`error`])),N({jsonrpc:Fu,id:Lu,method:X,params:X,result:B,error:X}).catchall(B).superRefine(as([`jsonrpc`,`method`,`params`,`error`])),N({jsonrpc:Fu,id:Lu,method:X,params:X,result:X,error:Ru}).catchall(B).superRefine(as([`jsonrpc`,`method`,`params`,`result`]))]);let zu=D().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});P({harnessId:V,nativeSessionId:zu,locator:B.optional(),formatVersion:z(1)}).superRefine(as([`locator`])),P({harnessId:V,nativeSessionId:zu,nativeTurnKey:zu,formatVersion:z(1)}),P({harnessId:V,nativeSessionId:zu,checkpointId:zu,locator:B.optional(),formatVersion:z(1)}).superRefine(as([`locator`]));let Bu=D().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Vu=R([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Hu=P({version:Bu,installation:Vu,phase:R([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:k().int().nonnegative(),downloadedBytes:k().int().nonnegative().optional(),totalBytes:k().int().positive().optional(),error:D().min(1).max(500).nullable(),serviceStopOutput:D().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});P({});let Uu=D().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`);P({currentVersion:Bu,installation:Vu.nullable(),latestVersion:Bu.nullable(),updateAvailable:j(),installationAvailable:j(),releaseNotes:D().min(1).max(2e4).nullable(),releaseNotesUrl:Uu.nullable(),status:Hu.nullable(),error:D().min(1).max(500).nullable()}),P({status:Hu}),P({status:Hu.nullable()});let Wu=P({icon:D().min(1).max(16).optional(),title:D().min(1).max(120),body:D().min(1).max(1200),contributors:M(D().min(1).max(39)).max(30)}),Gu=P({summary:D().min(1).max(600).optional(),themes:M(Wu).min(1).max(12)}),Ku=P({version:Bu,publishedAt:Sa(),url:D().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Gu.nullable(),en:Gu.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});P({manual:j().optional()}),P({announcement:Ku.nullable(),unread:j()}),P({version:Bu}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let qu=R([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);N({runningVersion:D().nullable(),installedVersion:D().nullable(),restartRequired:j(),remote:j(),updateSupported:j(),update:N({phase:qu,targetVersion:D().nullable(),error:D().nullable()})});let Ju=N({version:D().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();N({hostname:D().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable(),action:R([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:j().optional(),version:D().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),N({state:R([`installed`,`not-installed`])}).strict();let Z=D().min(1).max(1024),Yu={hostId:Z.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},Q={...Yu,threadId:Z},Xu=D().min(1).max(8e3),Zu={text:Xu,requestId:Z};I(`accepted`,[N({accepted:z(!0),startQueuedItemId:Z.optional()}),N({accepted:z(!1),code:R([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:D()})]),I(`available`,[N({available:z(!1)}),N({available:z(!0),items:M(N({id:Z,clientUserMessageId:Z,preview:D().max(801)})).max(100)})]);let Qu=I(`kind`,[P({kind:z(`hosts`)}),P({kind:z(`create`),...Yu,cwd:D().min(1).max(8192),epoch:Z}),P({kind:z(`projectHarnesses`),...Yu,epoch:Z}),P({kind:z(`inspectHarness`),...Yu,epoch:Z,cwd:D().min(1).max(8192),harnessId:Z}),P({kind:z(`startSelected`),...Yu,epoch:Z,cwd:D().min(1).max(8192),harnessId:Z,model:D().min(1).max(4096),serviceTier:R([`priority`,`ultrafast`]).optional(),reasoningEffort:Z.optional()}),P({kind:z(`status`),...Q}),P({kind:z(`list`),...Yu,cursor:D().nullable(),archived:j(),includeLoaded:z(!0).optional()}),P({kind:z(`read`),...Q,page:P({cursor:D().min(1).max(8192).nullable(),epoch:Z.optional(),sortDirection:R([`asc`,`desc`]).optional(),limit:k().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),P({kind:z(`usage`),...Q,epoch:Z}),P({kind:z(`configure`),...Q,epoch:Z,modelId:Z.optional(),serviceTier:Fs.optional(),thinkingOptionId:Z.optional(),permissionModeId:Z.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),P({kind:z(`prompt`),...Q,epoch:Z,text:Xu,requestId:Z.optional()}),P({kind:z(`queue`),...Q,epoch:Z}),P({kind:z(`delivery`),...Q,epoch:Z,action:I(`kind`,[P({kind:z(`enqueue`),...Zu}),P({kind:z(`steer`),...Zu,turnId:Z}),P({kind:z(`remove`),itemId:Z}),P({kind:z(`start`),itemId:Z,onlyIfHead:z(!0).optional()})])}),P({kind:z(`interrupt`),...Q,epoch:Z,turnId:Z}),P({kind:z(`rename`),...Q,epoch:Z,name:D().min(1).max(512)}),P({kind:z(`archive`),...Q,epoch:Z,archived:j()}),P({kind:z(`respond`),...Q,epoch:Z,requestId:F([Z,k().int()]),result:L(D(),yo())})]),$u=D().min(1).max(1024),ed=N({hostId:$u,displayName:D().min(1).max(1024),source:R([`codex-managed`,`discovered`]),sshAlias:D().max(1024).nullable(),sshHost:D().min(1).max(1024),sshPort:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable(),autoConnect:j(),connectionAnalyticsId:D().max(1024).optional()}),td=P({displayName:D().min(1).max(1024),hostname:D().min(1).max(1024),sshPort:k().int().min(1).max(65535).nullable(),identity:D().max(4096).nullable()});I(`action`,[P({action:z(`session`),operation:Qu}),P({action:z(`list`)}),P({action:z(`catalog`)}),P({action:z(`read-thread`),hostId:$u.refine(e=>e!==`local`),input:Nl}),P({action:z(`save`),draft:td,previous:ed.nullable()}),P({action:z(`remove`),previous:ed}),P({action:z(`connect`),hostId:$u,enabled:j()}),P({action:z(`state`),hostId:$u}),P({action:z(`runtime`),hostId:$u}),P({action:z(`update`),hostId:$u.refine(e=>e!==`local`),version:Ju.shape.version})]),F([P({result:B}),P({error:P({code:k().int(),message:D()})})]),P({prompt:D().trim().min(1).max(2e3),cwd:D().max(4096).nullable()}),D().trim().min(1).max(60).nullable();let nd=D().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),rd=F([D(),N({en:D()}).catchall(D())]),id=N({title:rd.optional(),description:rd.optional(),icon:D().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:D().optional()});N({extensions:M(N({id:nd,name:D().min(1).max(214),version:D().min(1).max(128),format:z(`dsh`),supportedTargets:ko([z(`web`)]),enabledTargets:M(z(`web`)).max(1),source:D().min(1).max(4096),projectUrl:D().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:D(),meta:id.optional(),loadError:D().optional()})),loadedIds:M(nd),safeMode:j(),storeError:D().optional()});let ad=D().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);N({spec:D().trim().min(1).max(4096),registry:ad.optional()}).strict(),N({id:nd,enabled:j()}).strict(),N({id:nd}).strict();let $=D().regex(/^[a-zA-Z0-9_-]{1,64}$/u),od=D().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),sd=R([`relay`,`tailscale`,`lan`,`custom`]),cd=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],ld=R(cd);new Set(cd);let ud=R([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]);N({peers:M(N({peerId:$,hostId:od,name:D().min(1).max(120),color:ld.optional(),origin:D().min(1).max(2048),transportKind:sd,encrypted:j(),enabled:j(),state:ud,latencyMs:k().int().nonnegative().optional(),version:D().max(128).optional(),platform:D().max(64).optional(),hostname:D().max(255).optional(),homeDir:D().max(4096).optional(),lastError:D().max(1e3).optional(),projectCount:k().int().nonnegative(),createdAt:D(),updatedAt:D()}))}),N({connectionUrl:D().min(1).max(4096).optional(),origin:D().min(1).max(2048).optional(),token:D().min(1).max(2048).optional(),name:D().trim().min(1).max(120).optional(),color:ld.optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),N({peerId:$,name:D().trim().min(1).max(120).optional(),color:ld.nullable().optional(),connectionUrl:D().min(1).max(4096).optional(),origin:D().min(1).max(2048).optional(),token:D().min(1).max(2048).optional(),enabled:j().optional()}),N({peerId:$}),N({removed:j()}),N({peerId:$.optional(),connectionUrl:D().min(1).max(4096).optional(),origin:D().min(1).max(2048).optional(),token:D().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let dd=N({id:D().min(1).max(1024),name:D().min(1).max(512),path:D().min(1).max(8192)});N({ok:j(),latencyMs:k().int().nonnegative().optional(),origin:D().max(2048).optional(),transportKind:sd.optional(),encrypted:j().optional(),version:D().max(128).optional(),platform:D().max(64).optional(),hostname:D().max(255).optional(),homeDir:D().max(4096).optional(),projectCount:k().int().nonnegative().optional(),projects:M(dd).optional(),error:D().max(1e3).optional()});let fd=N({id:D().min(1).max(1024),name:D().min(1).max(512),path:D().min(1).max(8192),threadIds:M(D().min(1).max(1024))}),pd=N({attachments:z(1).optional(),workspaceFiles:z(1).optional(),officePreview:z(1).optional()}),md=N({version:D().max(128),platform:D().max(64),hostname:D().max(255),homeDir:D().max(4096).optional(),epoch:D().min(1).max(256),projects:M(fd),capabilities:pd.optional()});P({threadId:D().min(1).max(1024),scope:D().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u).optional(),requestId:D().min(1).max(256).optional(),mode:R([`queue`,`steer`]).optional(),expectedTurnId:D().min(1).max(1024).nullable().optional(),content:M(I(`type`,[P({type:z(`text`),text:D()}),P({type:z(`file`),receiptId:D().min(1).max(128)})])).min(1).max(64)});let hd=N({ok:z(!1),error:N({code:D(),message:D(),details:L(D(),yo()).optional()})});F([N({ok:z(!0),value:N({receiptId:D().min(1),file:N({attachmentId:D(),name:D(),bytes:k().int().nonnegative()})})}),hd]),F([N({ok:z(!0),value:N({accepted:z(!0)})}),hd]);let gd=N({name:D().min(1).max(512),path:D().min(1).max(8192),kind:z(`directory`)});N({peerId:$,path:D().min(1).max(8192).optional()}),N({path:D().min(1).max(8192),parentPath:D().min(1).max(8192).nullable(),homeDir:D().min(1).max(8192).optional(),entries:M(gd)}),N({peerId:$,parentPath:D().min(1).max(8192),name:D().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),N({path:D().min(1).max(8192),name:D().min(1).max(255)}),N({peerId:$,path:D().min(1).max(8192),title:D().trim().min(1).max(255).optional()}),N({peerId:$,workspaceId:D().min(1).max(1024),title:D().trim().min(1).max(255)}),N({peerId:$,workspaceId:D().min(1).max(1024)}),N({workspaceId:D().min(1).max(1024).optional(),manifest:md}),z(1);function _d(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
113
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function Co(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;Co(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}let wo=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),To=[`oneOf`,`anyOf`];function Eo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Do(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!wo.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??Eo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ae(n,r,e.length===1?e[0]:Do(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=Eo(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function Oo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of wo)if(t in e)return;let n=t.filter(e=>To.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Do(t);else{let e=n[0],i=To.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Do([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,vo(e,r))}function ko(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):vo(i,s),vo(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())Co(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])Oo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}vo(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ae(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:jo(t,`input`,e.processors),output:jo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function E(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return E(r.element,n);if(r.type===`set`)return E(r.valueType,n);if(r.type===`lazy`)return E(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return E(r.innerType,n);if(r.type===`intersection`)return E(r.left,n)||E(r.right,n);if(r.type===`record`||r.type===`map`)return E(r.keyType,n)||E(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:E(r.in,n)||E(r.out,n);if(r.type===`object`){for(let e in r.shape)if(E(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(E(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(E(e,n))return!0;return!!(r.rest&&E(r.rest,n))}return!1}let Ao=(e,t={})=>n=>{let r=yo({...n,processors:t});return T(e,r),So(r,e),ko(r,e)},jo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=yo({...i??{},target:a,io:t,processors:n});return T(e,o),So(o,e),ko(o,e)},Mo=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},No=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Po=(e,t)=>{Mo(e,`minimum`,t),No(e,`maximum`,t)},Fo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Io=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Lo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Ro=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},zo=(e,t)=>Mo(e,`minimum`,t.minimum),Bo=(e,t)=>No(e,`maximum`,t.maximum),Vo=e=>(t,n)=>{Ro(t,n.format);let[r,i]=e[n.format];Mo(t,`minimum`,r),No(t,`maximum`,i)},Ho={greater_than:(e,t)=>Mo(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>No(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Fo(e,t.value),number_format:Vo(Ye),bigint_format:Vo(Xe),min_length:zo,max_length:Bo,length_equals:(e,t)=>Po(e,t.length),min_size:zo,max_size:Bo,size_equals:(e,t)=>Po(e,t.size),string_format:(e,t)=>{Ro(e,t.format),t.pattern&&Io(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Lo(e,t.mime)};function D(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Ho[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Mo(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Mo(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&No(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&No(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Fo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Lo(t,i.mime);for(let e of i.patterns??[])Io(t,e);return t}let Uo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Wo=/* @__PURE__ */ new Map([[Ur,Dn],[Gr,On]]),Go=e=>Wo.get(e)??e,Ko=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=D(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Uo[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Go);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},qo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=D(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):bo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Jo=(e,t,n,r)=>{n.type=`boolean`},Yo=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Xo=(e,t,n,r)=>{n.not={}},Zo=(e,t,n,r)=>{let i=e._zod.def,a=be(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},Qo=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(bo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(bo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},$o=(e,t,n,r)=>{bo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},es=(e,t,n,r)=>{bo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ts=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=D(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=T(a.element,t,{...r,path:[...r.path,`items`]})};function ns(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?ns(t.out):t.type===`catch`?ns(t.innerType):e._zod.optin}let rs=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&bo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ae(i.properties,e,T(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?ns(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=T(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},is=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>T(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},as=(e,t,n,r)=>{let i=e._zod.def,a=T(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=T(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},os=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>T(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?T(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?ns(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=D(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function ss(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=ss(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>ss(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?zn:Rn).source)),p}let cs=/* @__PURE__ */ new WeakMap;function ls(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of cs.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=ss(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}let us=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=D(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=T(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ae(i.patternProperties,Go(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=T(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=cs.get(t);n||(n=[],cs.set(t,n),t.deferred.push(()=>ls(t))),n.push(e)}i.additionalProperties=T(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&ns(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},ds=(e,t,n,r)=>{let i=e._zod.def,a=T(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},fs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ps=Symbol();function ms(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(bo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),ps):JSON.parse(o)}let hs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=ms(i.defaultValue,e,t,n,r);o!==ps&&(n.default=o)},gs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=ms(i.defaultValue,e,t,n,r);o!==ps&&(n._prefault=o)},_s=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{bo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},vs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;T(o,t,r);let s=t.seen.get(e);s.ref=o},ys=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},bs=(e,t,n,r)=>{let i=e._zod.def;T(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},xs=(e,t,n,r)=>{let i=e._zod.innerType;T(i,t,r);let a=t.seen.get(e);a.ref=i},Ss=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function Cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}let O=/*@__PURE__*/ y(`ZodError`,(e,t)=>{Vt.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Ss.has(n)||(Ss.add(n),Cs(n,`format`,e=>t=>Wt(e,t)),Cs(n,`flatten`,e=>t=>Ut(e,t)),Cs(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),Cs(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Se,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),ws=/* @__PURE__ */ Kt(O),Ts=/* @__PURE__ */ qt(O),Es=/* @__PURE__ */ Jt(O),Ds=/* @__PURE__ */ Xt(O),Os=/* @__PURE__ */ nn(O),ks=/* @__PURE__ */ rn(O),As=/* @__PURE__ */ an(O),js=/* @__PURE__ */ on(O),Ms=/* @__PURE__ */ sn(O),Ns=/* @__PURE__ */ cn(O),Ps=/* @__PURE__ */ ln(O),Fs=/* @__PURE__ */ un(O);function Is(){b.localeError||x(sa())}function Ls(){b.memoizer||x({memoizer:ia()})}let k=/*@__PURE__*/ y(`ZodType`,(e,t)=>(Is(),C.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(h(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ke(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(tl(e,t))},superRefine(e,t){return this.check(nl(e,t))},overwrite(e){return this.check(/* @__PURE__ */ oo(e))},optional(){return Pc(this)},exactOptional(){return Ic(this)},nullable(){return Rc(this)},nullish(){return Pc(Rc(this))},nonoptional(e){return Wc(this,e)},array(){return F(this)},or(e){return R([this,e])},and(e){return Tc(this,e)},transform(e){return Jc(this,Mc(e))},default(e){return Bc(this,e)},prefault(e){return Hc(this,e)},catch(e){return Kc(this,e)},pipe(e){return Jc(this,e)},readonly(){return Xc(this)},describe(e){let t=this.clone();return da.add(t,{description:e}),t},meta(...e){if(e.length===0)return da.get(this);let t=this.clone();return da.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return yt(this,`~standard`,{...dr(this),jsonSchema:{input:jo(this,`input`),output:jo(this,`output`)}})},set"~standard"(e){vt(this,`~standard`,e)},parse:function e(t,n){return ws(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ts(this,t,n,{callee:e})},safeParse(e,t){return Es(this,e,t)},async safeParseAsync(e,t){return Ds(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){vt(this,`spa`,e)},validate(e,t){return $t(this,e,t)},validateAsync(e,t){return tn(this,e,t)},encode:function e(t,n){return Os(this,t,n,{callee:e})},decode:function e(t,n){return ks(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await As(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await js(this,t,n,{callee:e})},safeEncode(e,t){return Ms(this,e,t)},safeDecode(e,t){return Ns(this,e,t)},async safeEncodeAsync(e,t){return Ps(this,e,t)},async safeDecodeAsync(e,t){return Fs(this,e,t)},toJSONSchema(e){return Ao(this,{})(e)},get description(){return da.get(this)?.description},get _def(){return this._zod.def}}),Rs=/*@__PURE__*/ y(`_ZodString`,(e,t)=>{fr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ko(e,t,n,r)},/*@__PURE__*/ bt({format:e=>D(e).format??null,minLength:e=>D(e).minimum??null,maxLength:e=>D(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ eo(...e))},includes(...e){return this.check(/* @__PURE__ */ ro(...e))},startsWith(...e){return this.check(/* @__PURE__ */ io(...e))},endsWith(...e){return this.check(/* @__PURE__ */ ao(...e))},min(...e){return this.check(/* @__PURE__ */ Qa(...e))},max(...e){return this.check(/* @__PURE__ */ Za(...e))},length(...e){return this.check(/* @__PURE__ */ $a(...e))},nonempty(...e){return this.check(/* @__PURE__ */ Qa(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ to(e))},uppercase(e){return this.check(/* @__PURE__ */ no(e))},trim(){return this.check(/* @__PURE__ */ co())},normalize(...e){return this.check(/* @__PURE__ */ so(...e))},toLowerCase(){return this.check(/* @__PURE__ */ lo())},toUpperCase(){return this.check(/* @__PURE__ */ uo())},slugify(){return this.check(/* @__PURE__ */ fo())}})),zs=/*@__PURE__*/ y(`ZodString`,(e,t)=>{fr.init(e,t),Rs.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ma(Ws,e))},url(e){return this.check(/* @__PURE__ */ ba(Js,e))},jwt(e){return this.check(/* @__PURE__ */ Fa(uc,e))},emoji(e){return this.check(/* @__PURE__ */ xa(Xs,e))},guid(e){return this.check(/* @__PURE__ */ ha(Gs,e))},uuid(e){return this.check(/* @__PURE__ */ ga(Ks,e))},uuidv4(e){return this.check(/* @__PURE__ */ _a(Ks,e))},uuidv6(e){return this.check(/* @__PURE__ */ va(Ks,e))},uuidv7(e){return this.check(/* @__PURE__ */ ya(Ks,e))},nanoid(e){return this.check(/* @__PURE__ */ Sa(Zs,e))},cuid(e){return this.check(/* @__PURE__ */ Ca(Qs,e))},cuid2(e){return this.check(/* @__PURE__ */ wa($s,e))},ulid(e){return this.check(/* @__PURE__ */ Ta(ec,e))},base64(e){return this.check(/* @__PURE__ */ Ma(sc,e))},base64url(e){return this.check(/* @__PURE__ */ Na(cc,e))},xid(e){return this.check(/* @__PURE__ */ Ea(tc,e))},ksuid(e){return this.check(/* @__PURE__ */ Da(nc,e))},ipv4(e){return this.check(/* @__PURE__ */ Oa(rc,e))},ipv6(e){return this.check(/* @__PURE__ */ ka(ic,e))},cidrv4(e){return this.check(/* @__PURE__ */ Aa(ac,e))},cidrv6(e){return this.check(/* @__PURE__ */ ja(oc,e))},e164(e){return this.check(/* @__PURE__ */ Pa(lc,e))},datetime(e){return this.check(/* @__PURE__ */ Ia(Bs,e))},date(e){return this.check(/* @__PURE__ */ La(Vs,e))},time(e){return this.check(/* @__PURE__ */ Ra(Hs,e))},duration(e){return this.check(/* @__PURE__ */ za(Us,e))}});function A(e){return/* @__PURE__ */ pa(zs,e)}let j=/*@__PURE__*/ y(`ZodStringFormat`,(e,t)=>{w.init(e,t),Rs.init(e,t)}),Bs=/*@__PURE__*/ y(`ZodISODateTime`,(e,t)=>{jr.init(e,t),j.init(e,t)}),Vs=/*@__PURE__*/ y(`ZodISODate`,(e,t)=>{Mr.init(e,t),j.init(e,t)}),Hs=/*@__PURE__*/ y(`ZodISOTime`,(e,t)=>{Nr.init(e,t),j.init(e,t)}),Us=/*@__PURE__*/ y(`ZodISODuration`,(e,t)=>{Pr.init(e,t),j.init(e,t)}),Ws=/*@__PURE__*/ y(`ZodEmail`,(e,t)=>{hr.init(e,t),j.init(e,t)}),Gs=/*@__PURE__*/ y(`ZodGUID`,(e,t)=>{pr.init(e,t),j.init(e,t)}),Ks=/*@__PURE__*/ y(`ZodUUID`,(e,t)=>{mr.init(e,t),j.init(e,t)});function qs(e){return/* @__PURE__ */ ga(Ks,e)}let Js=/*@__PURE__*/ y(`ZodURL`,(e,t)=>{Cr.init(e,t),j.init(e,t)});function Ys(e){return/* @__PURE__ */ ba(Js,e)}let Xs=/*@__PURE__*/ y(`ZodEmoji`,(e,t)=>{wr.init(e,t),j.init(e,t)}),Zs=/*@__PURE__*/ y(`ZodNanoID`,(e,t)=>{Tr.init(e,t),j.init(e,t)}),Qs=/*@__PURE__*/ y(`ZodCUID`,(e,t)=>{Er.init(e,t),j.init(e,t)}),$s=/*@__PURE__*/ y(`ZodCUID2`,(e,t)=>{Dr.init(e,t),j.init(e,t)}),ec=/*@__PURE__*/ y(`ZodULID`,(e,t)=>{Or.init(e,t),j.init(e,t)}),tc=/*@__PURE__*/ y(`ZodXID`,(e,t)=>{kr.init(e,t),j.init(e,t)}),nc=/*@__PURE__*/ y(`ZodKSUID`,(e,t)=>{Ar.init(e,t),j.init(e,t)}),rc=/*@__PURE__*/ y(`ZodIPv4`,(e,t)=>{Fr.init(e,t),j.init(e,t)}),ic=/*@__PURE__*/ y(`ZodIPv6`,(e,t)=>{Rr.init(e,t),j.init(e,t)}),ac=/*@__PURE__*/ y(`ZodCIDRv4`,(e,t)=>{zr.init(e,t),j.init(e,t)}),oc=/*@__PURE__*/ y(`ZodCIDRv6`,(e,t)=>{Vr.init(e,t),j.init(e,t)}),sc=/*@__PURE__*/ y(`ZodBase64`,(e,t)=>{Wr.init(e,t),j.init(e,t)}),cc=/*@__PURE__*/ y(`ZodBase64URL`,(e,t)=>{qr.init(e,t),j.init(e,t)}),lc=/*@__PURE__*/ y(`ZodE164`,(e,t)=>{Jr.init(e,t),j.init(e,t)}),uc=/*@__PURE__*/ y(`ZodJWT`,(e,t)=>{Xr.init(e,t),j.init(e,t)}),dc=/*@__PURE__*/ y(`ZodNumber`,(e,t)=>{Zr.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qo(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ bt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=D(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=D(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=D(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>D(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Ja(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},min(e,t){return this.check(/* @__PURE__ */ Ya(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Ka(e,t))},lte(e,t){return this.check(/* @__PURE__ */ qa(e,t))},max(e,t){return this.check(/* @__PURE__ */ qa(e,t))},int(e){return this.check(N(e))},safe(e){return this.check(N(e))},positive(e){return this.check(/* @__PURE__ */ Ja(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Ya(0,e))},negative(e){return this.check(/* @__PURE__ */ Ka(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ qa(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},step(e,t){return this.check(/* @__PURE__ */ Xa(e,t))},finite(){return this}}));function M(e){return/* @__PURE__ */ Ba(dc,e)}let fc=/*@__PURE__*/ y(`ZodNumberFormat`,(e,t)=>{Qr.init(e,t),dc.init(e,t)});function N(e){return/* @__PURE__ */ Va(fc,e)}let pc=/*@__PURE__*/ y(`ZodBoolean`,(e,t)=>{$r.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Jo(e,t,n,r)});function P(e){return/* @__PURE__ */ Ha(pc,e)}let mc=/*@__PURE__*/ y(`ZodNull`,(e,t)=>{ei.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r)});function hc(e){return/* @__PURE__ */ Ua(mc,e)}let gc=/*@__PURE__*/ y(`ZodUnknown`,(e,t)=>{ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function _c(){return/* @__PURE__ */ Wa(gc)}let vc=/*@__PURE__*/ y(`ZodNever`,(e,t)=>{ni.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r)});function yc(e){return/* @__PURE__ */ Ga(vc,e)}let bc=/*@__PURE__*/ y(`ZodArray`,(e,t)=>{Ls(),oi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ Qa(e,t))},nonempty(e){return this.check(/* @__PURE__ */ Qa(1,e))},max(e,t){return this.check(/* @__PURE__ */ Za(e,t))},length(e,t){return this.check(/* @__PURE__ */ $a(e,t))},unwrap(){return this.element}});function F(e,t){return/* @__PURE__ */ po(bc,e,t)}let xc=/*@__PURE__*/ y(`ZodObject`,(e,t)=>{Ls(),fi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),Et(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return V(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(h(this._zod.def,{catchall:e}))},passthrough(){return this.clone(h(this._zod.def,{catchall:_c()}))},loose(){return this.clone(h(this._zod.def,{catchall:_c()}))},strict(){return this.clone(h(this._zod.def,{catchall:yc()}))},strip(){return this.clone(h(this._zod.def,{catchall:void 0}))},extend(e){return et(this,e)},safeExtend(e){return nt(this,e)},merge(e){return rt(this,e)},pick(e){return Ze(this,e)},omit(e){return $e(this,e)},partial(...e){return it(Nc,this,e[0])},exactPartial(...e){return it(Fc,this,e[0],`exactPartial`)},required(...e){return at(Uc,this,e[0])}});function I(e,t){let n={type:`object`,shape:e??{},...g(t)};return new xc(n)}function L(e,t){return new xc({type:`object`,shape:e,catchall:yc(),...g(t)})}let Sc=/*@__PURE__*/ y(`ZodUnion`,(e,t)=>{mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.options=t.options});function R(e,t){return new Sc({type:`union`,options:e,...g(t)})}let Cc=/*@__PURE__*/ y(`ZodDiscriminatedUnion`,(e,t)=>{Sc.init(e,t),gi.init(e,t)});function z(e,t,n){return new Cc({type:`union`,options:t,discriminator:e,...g(n)})}let wc=/*@__PURE__*/ y(`ZodIntersection`,(e,t)=>{_i.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r)});function Tc(e,t){return new wc({type:`intersection`,left:e,right:t})}let Ec=/*@__PURE__*/ y(`ZodTuple`,(e,t)=>{Ls(),bi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Nc({type:`optional`,innerType:e}))})}});function Dc(e,t,n){let r=t instanceof C;return new Ec({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let Oc=/*@__PURE__*/ y(`ZodRecord`,(e,t)=>{Ls(),wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>us(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function B(e,t,n){return!t||!t._zod?new Oc({type:`record`,keyType:A(),valueType:e,...g(t)}):new Oc({type:`record`,keyType:e,valueType:t,...g(n)})}let kc=/*@__PURE__*/ y(`ZodEnum`,(e,t)=>{Ti.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new kc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new kc({...t,checks:[],...g(r),entries:i})}});function V(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new kc({type:`enum`,entries:n,...g(t)})}let Ac=/*@__PURE__*/ y(`ZodLiteral`,(e,t)=>{Ei.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function H(e,t){return new Ac({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let jc=/*@__PURE__*/ y(`ZodTransform`,(e,t)=>{Ls(),Di.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Pt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(gt(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(gt(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Mc(e){return new jc({type:`transform`,transform:e})}let Nc=/*@__PURE__*/ y(`ZodOptional`,(e,t)=>{ki.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e){return new Nc({type:`optional`,innerType:e})}let Fc=/*@__PURE__*/ y(`ZodExactOptional`,(e,t)=>{Ai.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e){return new Fc({type:`optional`,innerType:e})}let Lc=/*@__PURE__*/ y(`ZodNullable`,(e,t)=>{ji.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rc(e){return new Lc({type:`nullable`,innerType:e})}let zc=/*@__PURE__*/ y(`ZodDefault`,(e,t)=>{Mi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Bc(e,t){return new zc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Vc=/*@__PURE__*/ y(`ZodPrefault`,(e,t)=>{Pi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e,t){return new Vc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Uc=/*@__PURE__*/ y(`ZodNonOptional`,(e,t)=>{Fi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wc(e,t){return new Uc({type:`nonoptional`,innerType:e,...g(t)})}let Gc=/*@__PURE__*/ y(`ZodCatch`,(e,t)=>{Ri.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Kc(e,t){return new Gc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Dt(t)})}let qc=/*@__PURE__*/ y(`ZodPipe`,(e,t)=>{zi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.in=t.in,e.out=t.out});function Jc(e,t){return new qc({type:`pipe`,in:e,out:t})}let Yc=/*@__PURE__*/ y(`ZodReadonly`,(e,t)=>{Vi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xc(e){return new Yc({type:`readonly`,innerType:e})}let Zc=/*@__PURE__*/ y(`ZodLazy`,(e,t)=>{Ui.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Qc(e){return new Zc({type:`lazy`,getter:e})}let $c=/*@__PURE__*/ y(`ZodCustom`,(e,t)=>{Wi.init(e,t),k.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(e,t,n,r)});function el(e,t){return/* @__PURE__ */ mo($c,e??(()=>!0),t)}function tl(e,t={}){return/* @__PURE__ */ ho($c,e,t)}function nl(e,t){return/* @__PURE__ */ go(e,t)}function rl(e){return/* @__PURE__ */ Ia(Bs,e)}function il(e){return(t,n)=>{for(let r of e)Object.hasOwn(t,r)&&t[r]===void 0&&n.addIssue({code:`custom`,path:[r],message:`Explicit undefined is not valid JSON`})}}let al=R([A(),M(),P(),hc()]);function ol(e){let t=/* @__PURE__ */ new WeakSet,n=[{value:e,leaving:!1}];try{for(;n.length>0;){let e=n.pop();if(!e)break;if(e.leaving)t.delete(e.value);else if(typeof e.value==`object`&&e.value!==null){if(t.has(e.value))return!1;t.add(e.value),n.push({value:e.value,leaving:!0});for(let t of Object.values(e.value))n.push({value:t,leaving:!1})}}}catch{return!1}return!0}let sl=el(ol,{message:`JSON value must not contain circular references`}),cl=Qc(()=>R([al,F(cl),B(A(),cl)])),U=sl.pipe(cl);sl.pipe(F(cl));let ll=sl.pipe(B(A(),cl)),ul=L({code:A().min(1),message:A().min(1),retryable:P(),diagnostic:A().min(1).optional(),stage:A().min(1).optional(),durationMs:M().int().nonnegative().optional(),stderrTail:A().min(1).optional()}).superRefine(il([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),dl=A().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),fl=e=>A().min(1).max(e).refine(e=>e.trim().length>0),pl=B(dl,I({label:fl(256).optional(),description:fl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),ml=B(dl,fl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),hl=A().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),W=hl.brand(),G=hl.brand(),gl=hl.brand();hl.brand(),hl.brand();let _l=A().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),vl=_l.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),yl=I({modes:F(I({id:vl,label:_l.max(256),description:_l.max(1024).optional(),dangerous:P().optional(),localizations:pl.optional()}).strict()).min(1).max(32),defaultModeId:vl}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});I({threadId:G,permissionModeId:vl}).strict();let K=M().int().safe().nonnegative(),bl=M().finite().nonnegative(),xl=M().finite().min(0).max(100),Sl=I({version:R([H(3),H(4)]).optional(),requestId:A().min(1),turnId:A().min(1).max(1024),outputTokens:K,startedAtMs:K,completedAtMs:K}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Cl=I({version:R([H(2),H(3),H(4)]).optional(),value:bl,turnId:A().min(1).max(1024),at:K}).strict();I({outputTimings:F(Sl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Cl.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Cl.extend({value:K}).optional()}).strict();let wl=e=>ml.refine(t=>Object.values(t).every(t=>t.length<=e)),Tl=I({composerIndicators:F(I({kind:H(`countdown`),id:A().min(1).max(64),expiresAtUnix:K,label:wl(256).optional(),tooltip:wl(1024).optional()}).strict()).max(2).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,{message:`Composer indicator IDs must be unique`}).optional(),inputTokens:K.optional(),cachedInputTokens:K.optional(),cacheWriteInputTokens:K.optional(),outputTokens:K.optional(),outputTokensPerSecond:bl.optional(),sessionOutputTokensPerSecond:bl.optional(),apiOutputTokensPerSecond:bl.optional(),reasoningOutputTokens:K.optional(),totalTokens:K.optional(),totalCostUsd:bl.optional(),totalCredits:bl.optional(),contextUsagePercent:bl.optional(),cacheHitRatePercent:xl.optional(),contextWindowTokens:K.optional(),contextUsedTokens:K.optional(),planFiveHourUsedPercent:xl.optional(),planFiveHourResetsAtUnix:K.optional(),planSevenDayUsedPercent:xl.optional(),planSevenDayResetsAtUnix:K.optional(),sessionCacheHitRatePercent:xl.optional(),timeToFirstOutputMs:K.optional(),latestRequestTimeToFirstOutputMs:K.optional(),costSource:V([`publicPrice`,`native`]).optional(),unpricedModels:F(A().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),El=M().finite().min(0).max(100),Dl=V([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),Ol=I({id:A().min(1).max(256),label:A().min(1).max(256),localizations:pl.optional()}).strict(),kl=I({product:A().min(1),periodType:Dl.optional(),scope:Ol.optional(),localizations:pl.optional(),used:M().finite().nonnegative().optional(),limit:M().finite().nonnegative().optional(),unit:A().min(1).max(32).optional(),usagePercent:El,resetsAt:A().min(1).optional()}).strict(),Al=I({availableCount:M().int().safe().positive(),nextExpiresAt:A().min(1).optional(),expiresAt:F(A().min(1)).min(1).max(32).optional()}).strict(),jl=I({used:M().finite().nonnegative().optional(),limit:M().finite().nonnegative().optional(),unit:A().min(1).max(32).optional(),label:A().min(1).optional(),scope:Ol.optional(),localizations:pl.optional(),usedPercent:El,resetsAt:A().min(1).optional(),periodType:Dl,productUsage:F(kl).min(1).optional(),resetCredits:Al.optional()}).strict(),Ml=I({amount:M().finite().nonnegative(),currency:A().trim().min(1).max(8),label:A().trim().min(1).max(128).optional()}).strict();I({threadId:G,refresh:H(`exact`).optional()}).strict(),I({threadId:G,usage:Tl.nullable(),accountCredits:jl.optional(),accountBalance:Ml.optional(),accountCreditsSupported:P().optional()}).strict();let Nl=A().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Pl=A().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),Fl=V([`priority`,`ultrafast`]),q=I({id:Pl,serviceTier:Fl.optional()}).strict();function Il(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let J=Nl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand(),Ll=Nl.max(256),Rl=I({id:J,label:Nl.max(256)}).strict(),zl=I({ref:q,label:Nl.max(256),resolvedModelLabel:Ll.optional(),fastModel:q.optional(),supportedThinkingOptionIds:F(J).optional()}).strict().refine(e=>e.fastModel?.serviceTier===void 0||e.fastModel.id===e.ref.id,{path:[`fastModel`,`id`],message:`A tiered Fast Model must share the base Model ID`});function Bl(e,t){if(t)return e?.models.find(e=>Il(e.ref,t)||Il(e.fastModel,t))}let Vl=F(Rl).superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Thinking option IDs must be unique`,path:[r,`id`]}),n.add(i.id)}),Hl=I({models:F(zl),defaultModel:q.optional(),thinkingOptions:Vl,defaultThinkingOptionId:J.optional()}).strict().superRefine((e,t)=>{let n=[],r=new Set(e.thinkingOptions.map(({id:e})=>e));for(let[i,a]of e.models.entries()){n.some(e=>Il(e,a.ref))&&t.addIssue({code:`custom`,message:`Model Catalog refs must be unique`,path:[`models`,i,`ref`,`id`]}),n.push(a.ref),a.fastModel&&(n.some(e=>Il(e,a.fastModel))&&t.addIssue({code:`custom`,message:`Fast Model refs must be distinct and unique`,path:[`models`,i,`fastModel`]}),n.push(a.fastModel));let e=/* @__PURE__ */ new Set;for(let[n,o]of(a.supportedThinkingOptionIds??[]).entries())e.has(o)&&t.addIssue({code:`custom`,message:`Supported Thinking option IDs must be unique per Model`,path:[`models`,i,`supportedThinkingOptionIds`,n]}),e.add(o),r.has(o)||t.addIssue({code:`custom`,message:`Supported Thinking option must exist in the catalog`,path:[`models`,i,`supportedThinkingOptionIds`,n]})}e.defaultModel&&!Bl(e,e.defaultModel)&&t.addIssue({code:`custom`,message:`Default Model must exist in the Model Catalog`,path:[`defaultModel`,`id`]}),e.defaultThinkingOptionId&&!r.has(e.defaultThinkingOptionId)&&t.addIssue({code:`custom`,message:`Default Thinking option must exist in the catalog`,path:[`defaultThinkingOptionId`]})}),Ul=I({fork:P(),forkAcrossCwd:P(),rollbackLastTurn:P()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),Wl=V([`live`,`atCreate`]),Gl=I({configuration:I({selectModel:P(),selectThinkingOption:P(),selectPermissionMode:P(),permissionModeScope:Wl.default(`live`)}).strict(),history:Ul,subagents:I({observe:P(),readTranscript:P()}).strict().optional(),autonomousTurns:I({observe:P()}).strict().optional(),steer:P().optional(),persistentPlan:P().optional()}).strict();I({effectiveModel:q.optional(),resolvedModelLabel:Ll.optional(),effectiveThinkingOptionId:J.optional(),availableThinkingOptions:Vl.optional(),effectivePermissionModeId:vl.optional()}).strict().superRefine((e,t)=>{e.effectiveThinkingOptionId&&e.availableThinkingOptions&&!e.availableThinkingOptions.some(({id:t})=>t===e.effectiveThinkingOptionId)&&t.addIssue({code:`custom`,message:`Effective Thinking option must be currently available`,path:[`effectiveThinkingOptionId`]})});let Kl=I({open:H(!0)}).strict();R([I({status:H(`ready`),catalog:Hl,permissionModes:yl.optional(),capabilities:Gl,webUi:Kl.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),I({status:V([`notInstalled`,`unavailable`,`error`]),error:ul}).strict()]),I({harnessId:W,cwd:Nl.max(16384).optional(),refresh:P().optional(),purpose:H(`availability`).optional(),credentialAccess:V([`allow`,`retry`]).optional()}).strict(),I({harnessId:W}).strict(),I({}).strict(),I({threadId:G,model:q}).strict(),I({threadId:G,thinkingOptionId:J}).strict(),I({threadId:G,includeReferenceCapability:P().optional()}).strict(),z(`owner`,[I({owner:H(`codex`),locked:P(),effectiveModel:q.optional(),resolvedModelLabel:Ll.optional(),effectiveThinkingOptionId:J.optional(),effectivePermissionModeId:vl.optional(),history:Ul.optional(),supportsThreadReferences:H(!0).optional()}).strict(),I({owner:H(`external`),harnessId:Nl.max(256),transportModelId:Nl.max(8192),effectiveModel:q.optional(),resolvedModelLabel:Ll.optional(),effectiveThinkingOptionId:J.optional(),availableThinkingOptions:Vl.optional(),effectivePermissionModeId:vl.optional(),catalog:Hl.optional(),history:Ul,usage:Tl.optional(),locked:H(!0)}).strict()]),I({threadIds:F(G).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let ql=z(`owner`,[I({threadId:G,owner:H(`codex`)}).strict(),I({threadId:G,owner:H(`external`),harnessId:A().max(256).pipe(W)}).strict()]);I({threads:F(ql).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),I({threadId:G,text:A().optional()}).strict(),I({kind:H(`application`),value:A().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),kt}}).pipe(I({expectedTurnId:gl,clientUserMessageId:A().min(1),delivery:V([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),V([`activeTurn`,`newTurn`]),I({delivery:V([`official`,`activeTurn`,`newTurn`])}).strict();let Jl=A().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),Yl=Jl.pipe(W),Xl=Yl.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Zl=A().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),Ql=Ys().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),$l=I({en:A().max(4096),"zh-CN":A().max(4096).optional()}).strict(),eu=I({commands:F(I({terminal:A().max(256),command:A().max(4096)}).strict()).max(8),before:$l.optional(),after:$l.optional(),downloads:F(I({label:A().max(128),url:Ql}).strict()).max(8).optional()}).strict(),tu={id:Yl,name:A().trim().min(1).max(128),version:A().min(1).max(128),kind:H(`usage`).optional(),iconStyle:I({vector:I({viewBox:A().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:A().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:F(I({d:A().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:V([`evenodd`,`nonzero`]).optional(),fill:A().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:A().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:M().min(0).max(50).optional(),paddingRatio:M().min(0).max(.25).optional()}).strict().optional(),installation:eu.optional(),notice:$l.optional(),launchCommand:H(!0).optional(),links:I({website:Ql.optional(),documentation:Ql.optional(),installation:Ql.optional()}).strict().optional()};I({manifestVersion:H(1),...tu,adapterApiVersion:M().int().positive(),entry:Zl,icon:Zl.optional()}).strict();let nu=A().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),ru=I({...tu,icon:nu.optional()}).strict();I({}).strict(),I({plugins:F(ru.extend({id:Xl})).max(128)}).strict(),I({version:H(1),enabled:F(Yl).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let iu=Jl,au=V([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),ou=V([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),su=A().trim().min(1).max(128);function cu(e){switch(e.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()){case`png`:return`image/png`;case`jpg`:case`jpeg`:return`image/jpeg`;case`webp`:return`image/webp`;default:return}}let lu=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),uu=Zl.refine(e=>cu(e)!==void 0&&lu(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),du=A().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(Ys({protocol:/^https?$/u})).refine(e=>{let{username:t,password:n}=new URL(e);return!t&&!n&&!/[\\\s]/u.test(e)},`URL must not contain credentials, backslashes, or whitespace`);function fu(e){return L({en:e,"zh-CN":e})}let pu=fu(A().trim().min(1)),mu=F(ou).max(ou.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),hu=F(au).max(au.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),gu={key:A().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:pu,description:pu.optional()},_u={...gu,step:M().positive().optional(),default:M().optional()},vu=L({value:A(),label:pu}),yu=z(`type`,[L({...gu,type:H(`boolean`),default:P().optional()}),L({...gu,type:H(`string`),placeholder:pu.optional(),default:A().optional()}),L({..._u,type:H(`number`),min:M().optional(),max:M().optional()}),L({..._u,type:H(`range`),min:M(),max:M()}),L({...gu,type:H(`select`),options:F(vu).min(1),default:A().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),bu=I({manifestVersion:N().positive(),id:iu,name:R([su,fu(su)]),version:A().min(1).max(128),desktopApi:N().positive()}).passthrough().extend({manifestVersion:H(1),desktopApi:H(1),description:L({en:A().max(4096),"zh-CN":A().max(4096).optional()}).optional(),author:A().trim().min(1).max(128).optional(),repository:du.optional(),details:L({en:A().max(16384),"zh-CN":A().max(16384).optional()}).optional(),icon:uu.optional(),screenshots:F(uu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:L({script:Zl,style:Zl.optional()}).optional(),backend:L({script:Zl.refine(lu)}).optional(),slots:hu.default(()=>[]),settingsSchema:F(yu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:mu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),xu=A().regex(/^[a-f0-9]{64}$/u),Su=L({state:V([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:xu.optional(),error:A().optional(),conflictWith:iu.optional()});L({controllerPid:N().positive(),targetId:A().nullable(),updatedAt:rl(),handledReloadToken:qs().optional(),extensions:B(A(),Su),surfaces:B(A(),Su).optional()});let Cu=V([`official`,`community`]);function wu(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let Tu=du.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||wu(t)||t.origin===`https://github.com`&&/^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(t.pathname)||t.origin===`https://codeload.github.com`&&/^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(t.pathname)},`Expected a .zip download URL or a GitHub zipball URL`),Eu=L({id:iu,version:A().trim().min(1).max(128),name:pu.extend({en:su,"zh-CN":su}),description:fu(A().trim().min(1).max(4096)),details:fu(A().trim().min(1).max(16384)).optional(),author:A().trim().min(1).max(128),repository:du,stars:M().int().min(0).optional(),downloads:M().int().min(0).optional(),categories:mu.optional(),trustTier:Cu.default(`community`),icon:du.optional(),screenshots:F(du).max(4).optional(),downloadUrl:Tu,sha256:xu,slots:hu.optional(),publishedAt:A().optional(),updatedAt:A().optional(),minCodexHostVersion:A().optional()});L({schemaVersion:H(1),generatedAt:A(),extensions:F(Eu).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let Du=A().trim().min(1).max(128),Ou=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,ku=iu.refine(e=>!Ou.test(e),`Reserved extension ID`),Au=V([`desktop`,`web`]),ju=xu,Mu=qs(),Nu=Zl.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!Ou.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),Pu=bu.shape,Fu=(e,t=0)=>L({en:A().trim().min(t).max(e),"zh-CN":A().trim().min(t).max(e)}),Iu=e=>Nu.refine(t=>t.endsWith(e),`Expected a ${e} file`),Lu=Iu(`.mjs`),Ru=Iu(`.css`).optional(),zu=e=>e.normalize(`NFC`).toLowerCase(),Bu=L({manifestVersion:H(2),id:ku,name:Fu(128,1),version:A().trim().min(1).max(128),description:Fu(4096),details:Fu(16384).optional(),author:Pu.author,repository:Pu.repository,icon:Pu.icon.refine(e=>e===void 0||Nu.safeParse(e).success),screenshots:Pu.screenshots.refine(e=>e===void 0||e.every(e=>Nu.safeParse(e).success)),categories:Pu.categories,settingsSchema:Pu.settingsSchema,slots:Pu.slots.removeDefault().optional(),page:L({apiVersion:H(1),entry:Lu,style:Ru,title:Fu(128,1).optional()}).optional(),widget:L({apiVersion:H(1),entry:Lu,style:Ru}).optional(),desktop:L({apiVersion:H(1),script:Iu(`.js`),style:Ru}).optional(),web:L({apiVersion:H(1),entry:Lu.optional(),style:Ru}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:L({apiVersion:H(1),entry:Lu}).optional()}).refine(({page:e,widget:t,desktop:n,web:r,backend:i})=>!!(e||t||n||r||i),`Expected at least one page, widget, desktop, web, or backend entry`).refine(({page:e,widget:t,web:n,backend:r})=>!r||[e?.entry,t?.entry,n?.entry].every(e=>e===void 0||zu(e)!==zu(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function Vu({hasPage:e,hasWidget:t,hasDesktop:n,hasWeb:r,hasBackend:i}){if(e||t||i&&!n&&!r)return[`desktop`,`web`];let a=[];return n&&a.push(`desktop`),r&&a.push(`web`),a}let Hu=Du,Uu=N().nonnegative(),Wu=L({revision:Uu,enabled:F(ku).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)}),{downloadUrl:Gu,...Ku}=Eu.shape,qu=I({...Ku,id:ku,format:H(`codexhost`),targets:F(Au).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:L({page:N().positive().optional(),widget:N().positive().optional(),desktop:N().positive().optional(),web:N().positive().optional(),backend:N().positive().optional()}),downloadUrl:Gu.refine(e=>e.startsWith(`https://`),`Expected HTTPS`)}).refine(({targets:e,apis:t})=>{let n=Vu({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);I({schemaVersion:H(2),generatedAt:A().min(1),extensions:F(qu).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:du,fetchedAt:rl(),cached:P()});let Ju={id:ku},Yu={...Ju,activationId:Mu,digest:ju},Xu={...Ju,activationId:Yu.activationId.optional()},Zu=A().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),Qu=A().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function $u(e){return A().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let ed=L({type:H(`github`),repository:A().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Qu.optional(),tag:Qu.optional(),asset:A().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:Nu.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),td=R([L({type:H(`catalog`),...Ju}),ed,L({type:H(`zip`),base64:$u(67108864).min(4)}),L({type:H(`zip`),localZipPath:Zu}),L({type:H(`localDir`),localDir:Zu})]),nd=z(`type`,[L({type:H(`catalog`),...Ju}),ed,L({type:H(`zip`)}),L({type:H(`localDir`)})]),rd=L({...Yu,manifest:Bu,installedAt:rl(),source:nd.optional()}),id=e=>A().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),ad={desktopConflictWith:ku.optional()},od=V([`none`,`inactive`,`starting`,`running`,`failed`]),sd=z(`state`,[rd.extend({state:H(`valid`),enabled:P(),...ad,iconDataUrl:id(131072).optional(),screenshotDataUrls:F(id(524288)).max(4).optional(),backendState:od.optional(),backendError:A().optional()}),L({state:V([`invalid`,`incompatible`]),id:A().min(1),enabled:P(),error:A()})]);L({revision:Uu,configuration:Wu,diagnostics:F(A()),extensions:F(sd)}),L({revision:Uu,extensions:F(rd.extend({...ad,settingsRevision:Uu})).max(64)});let Y={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`},cd=Object.freeze(Object.values(Y));new Set(cd),L({});let ld={expectedRevision:Uu};L({...Ju,...ld}),rd.extend({replaced:P()}),z(`state`,[L({state:H(`saved`),configuration:Wu}),L({state:H(`revision-conflict`),revision:Uu})]),L({...Xu,digest:Yu.digest.optional(),path:Nu}),L({mimeType:A().min(1),base64:$u(16777216),digest:Yu.digest}),L({settingsRevision:Uu,values:ll}),Y.list,Y.snapshot,Y.catalog,L({forceRefresh:P().optional()}),Y.install,L({source:td}),Y.update,L({...Ju,expectedDigest:Yu.digest,expectedActivationId:Yu.activationId.optional(),source:td.optional()}),Y.enable,Y.disable,Y.uninstall,L({...Ju,removeData:P().optional(),expectedDigest:Yu.digest.optional()}),L({...Ju,removed:P()}),Y.recover,L({expectedRevision:ld.expectedRevision.optional()}),Y.asset,Y.settingsGet,L(Xu),Y.settingsSet,L({...Xu,expectedSettingsRevision:Uu,values:ll}),Y.backendInvoke,L({...Xu,method:Hu,params:U.optional()}),L({result:U}),I({threadId:G}).strict(),I({confirmed:P()}).strict(),[...cd],I({sections:F(I({id:A().min(1),name:A().min(1),threads:F(ll)}).strict())}).strict(),I({threadId:A().min(1).max(1024),sectionId:A().min(1).max(1024).nullable()}).strict(),I({threadIds:F(A().min(1))}).strict(),I({threadId:A().min(1).max(1024),pinned:P()}).strict(),I({}).strict(),I({parents:B(A().min(1),A().min(1))}).strict(),I({prompt:A().max(16384).optional()}).strict(),I({projects:F(I({id:A(),name:A(),rootPaths:F(A())})),assignments:B(A(),A()),projectless:F(A()),pinned:F(A()),sectionProjects:B(A(),F(A())).optional()});let ud=B(A(),_c()),dd=I({epoch:A().uuid(),sequence:M().int().nonnegative()});z(`type`,[I({type:H(`skills-changed`),cursor:dd,cwd:A().optional()}),I({type:H(`harness-inspection-changed`),cursor:dd,harnessId:A().min(1)}),I({type:H(`display-settings-changed`),cursor:dd}),I({type:H(`preferences-changed`),cursor:dd,revision:M().int().nonnegative()}),I({type:H(`extensions-changed`),cursor:dd,revision:Uu}),I({type:H(`hello`),version:H(1),cursor:dd,reset:P()}),I({type:H(`changed`),cursor:dd,threadId:A().min(1),method:A().min(1)})]);let fd=z(`type`,[I({type:H(`text`),id:A(),prompt:A(),secret:P().optional(),optional:P().optional()}),I({type:H(`choice`),id:A(),prompt:A(),multiple:P(),allowOther:P(),optional:P().optional(),options:F(I({value:A(),label:A(),description:A().optional()}))})]),pd=z(`type`,[I({type:H(`approval`),title:A(),description:A().optional(),subject:_c().optional(),actions:F(I({id:A(),label:A(),effect:A()}))}),I({type:H(`question`),title:A().optional(),questions:F(fd)})]),md=I({requestId:R([A(),M().int()]),threadId:A(),kind:V([`approval`,`question`]),interaction:pd,request:ud}),hd=I({id:A().min(1),clientUserMessageId:A().min(1),input:F(ud),presentationInput:F(ud).nullable().optional()}).passthrough();I({fields:F(I({path:F(R([A(),M().int().nonnegative()])),originalLength:M().int().nonnegative()}))});let gd=I({id:A().min(1),status:A().min(1),codexhostTurnOutcome:I({status:H(`unknown`),reason:A()}).optional(),items:F(I({id:A().min(1),type:A().min(1)}).passthrough()),codexhostFileOperations:F(I({beforeItemId:A().nullable(),item:I({id:A().min(1),type:A().min(1)}).passthrough()})).optional(),error:I({message:A().optional()}).passthrough().nullable().optional(),fingerprint:A().min(1).optional(),unchanged:H(!0).optional()}).passthrough(),_d=I({id:A().min(1).max(512),fingerprint:A().min(1).max(128)});I({threadId:A().min(1),knownTurns:F(_d).max(64).optional(),truncateToolOutput:P().optional()});let vd=I({harnessId:A().min(1),nativeSessionId:A().min(1)});I({cursor:dd,activeTurnId:A().min(1).nullable().optional(),command:I({name:A().min(1),turn:gd,subsequentTurnId:A().min(1).optional()}).optional(),thread:I({id:A().min(1),cwd:A(),modelProvider:A().min(1),createdAt:M(),updatedAt:M(),status:I({type:A()}).passthrough(),name:A().nullable().optional(),preview:A().optional(),codexhostImportSource:vd.optional(),turns:F(gd).length(0)}).passthrough(),turnsPage:I({data:F(gd).max(5),nextCursor:A().nullable()}),configuration:I({native:I({model:A().min(1).max(1024).optional(),reasoningEffort:A().min(1).max(128).optional()}).optional(),effectiveModel:q.optional(),effectiveThinkingOptionId:J.optional(),effectivePermissionModeId:vl.optional()}),queue:I({items:F(hd),pausedReason:V([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:F(md)}),I({version:H(1),owner:H(`service`).optional(),pid:M().int().positive(),port:M().int().min(1).max(65535),token:A().regex(/^[0-9a-f]{64}$/u),startedAt:M(),epoch:A().uuid()}),I({epoch:A().uuid(),threadId:A().min(1),requestId:R([A(),M().int()]),result:ud}),I({includeArchived:P().optional(),officialCursor:I({live:A().nullable(),archived:A().nullable().optional()}).strict().optional(),scope:I({cwd:A().min(1).max(4096),excludeCwds:F(A().min(1).max(4096)).max(1024)}).strict().optional()}).strict(),I({threads:F(ll),ownership:F(ql),archivedThreadIds:F(G),officialCursor:I({live:A().nullable(),archived:A().nullable().optional()}).strict().optional()}).strict();let yd=V([`running`,`waiting`,`idle`,`unknown`]),bd=L({harnessId:W,title:A().optional(),status:yd,archived:P()}),xd=L({revision:N().nonnegative(),parents:B(G,G),nodes:B(G,bd),truncated:P()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,nodes:t})=>Object.entries(e).every(([e,n])=>Object.hasOwn(t,e)&&Object.hasOwn(t,n)),`Missing Thread tree node`),Sd=A().min(1).max(128);L({});let Cd=L({subscriptionId:Sd});L({}),Cd.extend({snapshot:xd});let wd=A().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);I({available:P()}).strict(),I({path:A().min(1),mimeType:wd}).strict();let Td=V([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);z(`ok`,[I({ok:H(!0),text:A()}).strict(),I({ok:H(!1),error:I({code:Td}).strict()}).strict()]),I({threadId:G.optional(),cwd:A().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Ed=I({name:A().min(1).regex(/^[^\s[\]]+$/u),description:A().optional(),path:A().min(1),scope:V([`project`,`global`]),source:A().min(1)}).strict();I({revision:M().int().nonnegative(),complete:P(),skills:F(Ed),warnings:F(A()).optional()}).strict(),I({cwd:A().min(1).optional()}).strict();let Dd=I({kind:V([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:A().min(1)}).strict(),Od=z(`status`,[I({status:H(`not-installed`)}),I({status:H(`not-running`)}),I({status:H(`not-logged-in`)}),I({status:H(`https-disabled`)}),I({status:H(`not-serving`),command:A()}),I({status:H(`occupied`),target:A()}),I({status:H(`serving`),url:A(),funnel:P()}),I({status:H(`error`),message:A()})]);I({state:Od,error:A().optional()}).strict();let kd=z(`status`,[I({status:H(`on`)}),I({status:H(`off`)}),I({status:H(`invalid`),reason:A()})]),Ad=I({lan:P(),autostart:kd}).strict(),jd=I({expiresAt:A().optional(),issuing:P(),failure:I({detail:A().optional(),retryAt:A(),paused:P()}).optional()}),Md=z(`status`,[I({status:H(`off`),reason:V([`invite`,`name-taken`,`banned`]).optional()}),I({status:H(`connecting`),reason:V([`full`,`unreachable`]).optional()}),I({status:H(`connected`),url:A(),certificate:jd}),I({status:H(`missing-certificate`),url:A(),certificate:jd}),I({status:H(`stopped`),reason:V([`replaced`,`rejected`,`unsupported-version`])})]);A().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),A().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let Nd=V([`official`,`self-hosted`]);I({secret:A().min(1),lastUsedAt:M().nullable(),networkUrls:F(Dd),directCandidates:F(Dd).optional(),tailscale:Od,background:Ad.optional(),relay:I({state:Md,enabled:P(),kind:Nd,officialHost:A(),customHost:A().optional(),officialHostname:A().optional(),customHostname:A().optional(),quotaUntil:A().optional()}).strict().optional()}).strict();let Pd=L({threadId:A().min(1).max(1024),view:V([`result`,`messages`]),from:M().int().min(1).max(2**53-1).optional(),to:M().int().min(1).max(2**53-1).optional()}),Fd=I({id:A().min(1).max(256),harnessId:A().min(1),label:A().min(1).max(512),provider:V([`openai-codex`,`xai`])}).strict(),Id=A().regex(/^[a-z][a-z0-9-]{0,47}$/),Ld=I({name:Id,source:Fd,importedAt:A()}).strict(),Rd=z(`action`,[I({action:H(`list`)}).strict(),I({action:H(`import`),sourceId:A().min(1).max(256),name:Id,confirmed:H(!0)}).strict(),I({action:H(`reimport`),sourceId:A().min(1).max(256),name:Id,confirmed:H(!0)}).strict(),I({action:H(`remove`),name:Id,confirmed:H(!0)}).strict()]),zd=I({provider:A().min(1).max(128),type:V([`oauth`,`api_key`,`unknown`]),label:A().min(1).max(512).optional(),vendor:V([`openai-codex`,`xai`]).optional()}).strict();I({sources:F(Fd),targets:F(I({harnessId:A(),providers:F(V([`openai-codex`,`xai`])),imports:F(Ld),others:F(zd).default([])}).strict())}).strict(),I({targetHarnessId:A().min(1).max(128).optional(),request:Rd}).strict(),I({events:P()});let Bd=F(L({agent:A().min(1).max(128),section:V([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);L({entries:Bd.nullable()}),L({}),L({entries:Bd,initializeOnly:P().optional()});let Vd=L({enabled:P(),timeoutMinutes:M().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let Hd=A().regex(/^external$/u),Ud=W.transform(e=>String(e)),Wd=L({model:q.optional(),thinkingOptionId:J.optional(),permissionModeId:vl.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`),Gd=L({lastHarness:W.optional(),byHarness:B(Ud,Wd)}),Kd=L({model:q.optional(),thinkingOptionId:J.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),qd=L({byHarness:B(Ud,Kd)}),Jd=A().min(1).max(1024),Yd=L({idleRelease:Vd.optional(),favorites:B(Ud,F(Jd).max(2048)).default({}),newThread:Gd.optional(),delegation:qd.optional()});L({scope:Hd,revision:M().int().nonnegative(),values:Yd}),L({scope:Hd.default(`external`)});let Xd=z(`kind`,[L({kind:H(`idleRelease`),value:Vd}),L({kind:H(`favorite`),harnessId:W,modelId:Jd,enabled:P()}),L({kind:H(`favorites`),harnessId:W,modelIds:F(Jd).max(2048)}),L({kind:H(`newThread`),lastHarness:W.optional(),harnessId:W.optional(),configuration:Wd.optional()}),L({kind:H(`delegation`),harnessId:W,configuration:Kd.nullable()})]);L({scope:Hd.default(`external`),operations:F(Xd).min(1).max(256),initializeOnly:P().optional(),expectedRevision:M().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),L({version:H(1),revision:M().int().nonnegative(),scopes:B(Hd,Yd)});let Zd=M().finite().nonnegative(),Qd=L({input:Zd,output:Zd,cacheRead:Zd.optional(),cacheWrite:Zd.optional(),cacheWrite1h:Zd.optional()}),$d=A().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);L({path:A(),entries:F(L({key:A(),price:Qd})),error:A().nullable()}),L({}),L({key:$d,price:Qd.nullable(),previousKey:$d.optional()}),L({model:$d});let ef=L({official:P().optional(),canonicalModelId:A().min(1).optional(),provider:A().min(1).max(512),model:A().min(1).max(512),price:Qd});L({price:Qd.nullable(),suggestions:F(ef).max(6).optional()});let tf=[`today`,`7d`,`30d`,`90d`,`all`],X=M().int().min(0).max(2**53-1),nf=A().regex(/^\d{4}-\d{2}-\d{2}$/u),rf=A().min(1).max(128),af=A().min(1).max(512),of=A().min(1).max(4096);L({range:V(tf),timeZone:A().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:rf.optional(),model:af.nullable().optional(),project:of.nullable().optional(),date:nf.optional()});let sf=L({requests:X,inputTokens:X,cachedInputTokens:X,cacheWriteInputTokens:X,cacheKnownInputTokens:X,cacheHitCachedInputTokens:X,cacheHitInputTokens:X,outputTokens:X,reasoningOutputTokens:X,costUsd:M().finite().min(0),unpricedRequests:X,unmeteredRequests:X}),cf=sf.shape,lf=L({harness:rf,sessionId:A().min(1).max(512),project:of.nullable(),title:A().min(1).max(200).optional(),models:F(af).max(16),firstAtMs:X,lastAtMs:X,...cf});L({range:V(tf),from:nf.nullable(),to:nf,filters:L({harness:rf.nullable(),model:af.nullable(),unknownModel:P(),project:of.nullable(),unknownProject:P(),date:nf.nullable()}),reading:L({complete:P(),sources:X,read:X}),failures:F(L({harness:rf,message:A().max(2048)})).max(256),options:L({harnesses:F(rf).max(256),models:F(af.nullable()).max(4096),projects:F(of.nullable()).max(4096)}),modelLabels:F(L({harness:rf,model:af,label:af})).max(4096).optional(),credits:F(L({harness:rf,model:af.nullable(),credits:M().finite().min(0),reportedRequests:X,requests:X})).max(4096).optional(),totals:sf,daily:F(L({date:nf,harness:rf,...cf})).max(2e5),hourly:F(L({weekday:M().int().min(0).max(6),hour:M().int().min(0).max(23),...cf})).max(168),byHarness:F(L({harness:rf,...cf})).max(256),byModel:F(L({model:af.nullable(),...cf,harnessPricedRequests:X})).max(4096),byProject:F(L({project:of.nullable(),...cf})).max(4096),sessions:F(lf).max(100),recentSessions:F(lf).max(100).optional()}),I({threadId:G}),I({discarded:P()});let uf=z(`type`,[I({id:A().min(1),type:H(`choice`),prompt:A(),options:F(I({value:A().min(1),label:A(),description:A().optional()})).min(1),multiple:P(),allowOther:P(),optional:P()}),I({id:A().min(1),type:H(`text`),prompt:A(),multiline:P(),secret:H(!1),optional:P(),placeholder:A().optional(),prefill:A().optional()})]),df=I({interactionId:A().min(1),turnId:A().min(1),title:A().optional(),questions:F(uf).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});L({threadId:A().min(1)}),I({questions:F(df)}),L({threadId:A().min(1),turnId:A().min(1),interactionId:A().min(1),answers:B(A(),F(A())),cancelled:P().default(!1)}),I({accepted:H(!0)});let ff=`codexhostActiveTurnId`,pf=/* @__PURE__ */ new Set([ff,`codexhostTurnChanges`,`codexhostToolOutput`]),mf=I({path:A(),oldText:A().nullable(),newText:A()});I({sessionId:A().min(1),turn:M().int().nonnegative(),path:A().min(1).optional()}),I({diffs:F(mf)}),L({}),L({}),I({reference:I({sessionId:A().min(1),epoch:A().min(1),turn:M().int().nonnegative(),seq:M().int().nonnegative(),callId:A().min(1),part:M().int().nonnegative(),version:A().min(1)}),length:M().int().nonnegative(),bytes:M().int().nonnegative()}),L({title:A().trim().min(1).max(200),type:V([`info`,`warning`,`danger`]),body:A().trim().min(1).max(16384)}),L({}),L({url:A().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status`.split(`.`));let hf=V([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),gf=V([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);L({threadId:A(),title:A(),harnessId:A(),state:hf,reason:gf,inactiveMs:M().nonnegative()}),L({threadId:G,turnId:gl});let _f=I({email:A().trim().min(1).max(320).optional(),label:A().trim().min(1).max(256).optional(),plan:A().trim().min(1).max(128).optional(),credits:jl.optional(),balance:Ml.optional()}).strict();function vf(e){return e.refine(e=>{let t=e;return t.credits!==void 0||t.balance!==void 0},{message:`Account must report either credits or a balance`})}let yf=vf(_f),bf={harnessId:W,harnessName:A().trim().min(1).max(128)},xf=I(bf).strict();I({}).strict(),I({sources:F(xf).max(128)}).strict(),I({harnessId:W,refresh:P().optional()}).strict(),I({...bf,account:yf.nullable(),accounts:F(yf).max(8).optional()}).strict(),I({refresh:P().optional()}).strict(),I({accounts:F(vf(_f.extend(bf))).max(128)}).strict(),I({harnessId:Xl,model:q.optional(),thinkingOptionId:J.optional(),permissionModeId:vl.optional(),prewarm:H(!0).optional()}).strict();let Sf=A().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);I({harnessId:Xl}).strict().extend({path:Sf.nullable()}),I({path:Sf.nullable(),restartRequired:P()}).strict(),I({harnessId:W,action:V([`check`,`update`,`install`]),confirmedVersion:A().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let Cf=I({currentVersion:A().min(1).max(128),latestVersion:A().min(1).max(128),updateAvailable:P(),canUpdate:P(),latestVerifiedVersion:A().min(1).max(128).optional(),confirmationRequired:H(!0).optional(),versionKind:V([`cli`,`application`]).optional(),manualUpdateUrl:Ys().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:A().max(2048).optional(),messageCode:A().min(1).max(128).optional(),notice:ml.optional(),latestVersionKind:V([`unknown`,`tracking-branch`]).optional()}).strict();I({taskId:A().uuid()}).strict(),z(`status`,[I({taskId:A().uuid(),status:H(`running`)}).strict(),I({taskId:A().uuid(),status:H(`succeeded`),result:Cf}).strict(),I({taskId:A().uuid(),status:H(`failed`),error:I({code:M().int(),message:A().min(1).max(2048)}).strict()}).strict()]);let wf=A().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Tf=A().trim().min(1),Ef=V([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),Df=I({accountId:wf,label:Tf.max(256),email:A().email().max(320).optional(),planType:Ef.optional()}).strict(),Of=V([`ready`,`unavailable`]);I({version:H(2),currentAccountId:wf.nullable(),phase:Of,revision:M().int().nonnegative(),instanceId:Tf.max(1024).optional(),accounts:F(Df).max(1)}).strict(),I({accountId:wf,refresh:P().optional()}).strict(),I({accountId:wf,usage:Tl.nullable(),accountCredits:jl.optional(),freshness:V([`live`,`cached`]),observedAt:A().datetime().nullable()}).strict();let kf=1e3,Af=A().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),jf=Af.max(1024),Mf=I({nativeSessionId:jf,title:Af.max(4096).nullable(),updatedAt:M().int().nonnegative().max(864e13),cwd:Af.max(16384),running:P().nullable()}).strict();I({}).strict(),I({harnesses:F(I({harnessId:Xl,name:Af.max(128)}).strict()).max(128)}).strict(),I({harnessId:Xl,query:A().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:M().int().nonnegative().safe().optional(),limit:M().int().min(1).max(kf).optional()}).strict(),I({candidates:F(Mf).max(kf),total:M().int().nonnegative().safe()}).strict(),I({harnessId:Xl,nativeSessionId:jf}).strict(),I({threadId:Af.max(1024).pipe(G)}).strict();let Nf=A().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Pf=jf,Ff=Mf;I({}).strict(),I({candidates:F(Ff).max(1e3)}).strict(),I({nativeSessionId:Pf}).strict(),I({threadId:Nf.max(1024).pipe(G)}).strict(),I({threadId:G,lastTurnId:gl}).strict(),I({threadId:G}).strict();let If=A().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();I({commands:F(I({id:If,invocation:A().min(1).max(128),label:A().trim().min(1).max(128),description:A().trim().min(1).max(512).optional(),localizations:pl.optional(),argumentMode:V([`none`,`text`]),kind:V([`command`,`skill`]).optional()}).strict()),warnings:F(A().min(1)).optional(),source:V([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),I({harnessId:W,cwd:A().min(1).optional()}).strict(),I({threadId:G}).strict(),I({threadId:G,commandId:If,turnId:gl.optional(),arguments:ll.optional()}).strict(),I({accepted:H(!0),turnId:gl.optional()}).strict();let Lf=H(`2.0`).optional(),Z=yc().optional(),Rf=A().min(1),zf=R([A(),M().int()]),Bf=I({code:M().int(),message:A(),data:U.optional()}).catchall(U).superRefine(il([`data`]));R([I({jsonrpc:Lf,id:zf,method:Rf,params:U.optional(),result:Z,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`params`,`result`,`error`])),I({jsonrpc:Lf,id:Z,method:Rf,params:U.optional(),result:Z,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`id`,`params`,`result`,`error`])),I({jsonrpc:Lf,id:zf,method:Z,params:Z,result:U,error:Z}).catchall(U).superRefine(il([`jsonrpc`,`method`,`params`,`error`])),I({jsonrpc:Lf,id:zf,method:Z,params:Z,result:Z,error:Bf}).catchall(U).superRefine(il([`jsonrpc`,`method`,`params`,`result`]))]);let Vf=A().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});L({harnessId:W,nativeSessionId:Vf,locator:U.optional(),formatVersion:H(1)}).superRefine(il([`locator`])),L({harnessId:W,nativeSessionId:Vf,nativeTurnKey:Vf,formatVersion:H(1)}),L({harnessId:W,nativeSessionId:Vf,checkpointId:Vf,locator:U.optional(),formatVersion:H(1)}).superRefine(il([`locator`]));let Hf=A().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Uf=V([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Wf=L({version:Hf,installation:Uf,phase:V([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),updatedAt:M().int().nonnegative(),downloadedBytes:M().int().nonnegative().optional(),totalBytes:M().int().positive().optional(),error:A().min(1).max(500).nullable(),serviceStopOutput:A().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});L({});let Gf=A().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`);L({currentVersion:Hf,installation:Uf.nullable(),latestVersion:Hf.nullable(),updateAvailable:P(),installationAvailable:P(),releaseNotes:A().min(1).max(2e4).nullable(),releaseNotesUrl:Gf.nullable(),status:Wf.nullable(),error:A().min(1).max(500).nullable()}),L({status:Wf}),L({status:Wf.nullable()});let Kf=L({icon:A().min(1).max(16).optional(),title:A().min(1).max(120),body:A().min(1).max(1200),contributors:F(A().min(1).max(39)).max(30)}),qf=L({summary:A().min(1).max(600).optional(),themes:F(Kf).min(1).max(12)}),Jf=L({version:Hf,publishedAt:rl(),url:A().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:qf.nullable(),en:qf.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});L({manual:P().optional()}),L({announcement:Jf.nullable(),unread:P()}),L({version:Hf}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Yf=V([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);I({runningVersion:A().nullable(),installedVersion:A().nullable(),restartRequired:P(),remote:P(),updateSupported:P(),update:I({phase:Yf,targetVersion:A().nullable(),error:A().nullable()})});let Xf=I({version:A().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();I({hostname:A().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable(),action:V([`inspect`,`install`,`update`,`repair`,`uninstall`]),uninstallPackage:P().optional(),version:A().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),I({state:V([`installed`,`not-installed`])}).strict();let Q=A().min(1).max(1024),Zf={hostId:Q.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},$={...Zf,threadId:Q},Qf=A().min(1).max(8e3),$f={text:Qf,requestId:Q};z(`accepted`,[I({accepted:H(!0),startQueuedItemId:Q.optional()}),I({accepted:H(!1),code:V([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:A()})]),z(`available`,[I({available:H(!1)}),I({available:H(!0),items:F(I({id:Q,clientUserMessageId:Q,preview:A().max(801)})).max(100)})]);let ep=z(`kind`,[L({kind:H(`hosts`)}),L({kind:H(`create`),...Zf,cwd:A().min(1).max(8192),epoch:Q}),L({kind:H(`projectHarnesses`),...Zf,epoch:Q}),L({kind:H(`inspectHarness`),...Zf,epoch:Q,cwd:A().min(1).max(8192),harnessId:Q}),L({kind:H(`startSelected`),...Zf,epoch:Q,cwd:A().min(1).max(8192),harnessId:Q,model:A().min(1).max(4096),serviceTier:V([`priority`,`ultrafast`]).optional(),reasoningEffort:Q.optional()}),L({kind:H(`status`),...$}),L({kind:H(`list`),...Zf,cursor:A().nullable(),archived:P(),includeLoaded:H(!0).optional()}),L({kind:H(`read`),...$,page:L({cursor:A().min(1).max(8192).nullable(),epoch:Q.optional(),sortDirection:V([`asc`,`desc`]).optional(),limit:M().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),L({kind:H(`usage`),...$,epoch:Q}),L({kind:H(`configure`),...$,epoch:Q,modelId:Q.optional(),serviceTier:Fl.optional(),thinkingOptionId:Q.optional(),permissionModeId:Q.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),L({kind:H(`prompt`),...$,epoch:Q,text:Qf,requestId:Q.optional()}),L({kind:H(`queue`),...$,epoch:Q}),L({kind:H(`delivery`),...$,epoch:Q,action:z(`kind`,[L({kind:H(`enqueue`),...$f}),L({kind:H(`steer`),...$f,turnId:Q}),L({kind:H(`remove`),itemId:Q}),L({kind:H(`start`),itemId:Q,onlyIfHead:H(!0).optional()})])}),L({kind:H(`interrupt`),...$,epoch:Q,turnId:Q}),L({kind:H(`rename`),...$,epoch:Q,name:A().min(1).max(512)}),L({kind:H(`archive`),...$,epoch:Q,archived:P()}),L({kind:H(`respond`),...$,epoch:Q,requestId:R([Q,M().int()]),result:B(A(),_c())})]),tp=A().min(1).max(1024),np=I({hostId:tp,displayName:A().min(1).max(1024),source:V([`codex-managed`,`discovered`]),sshAlias:A().max(1024).nullable(),sshHost:A().min(1).max(1024),sshPort:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable(),autoConnect:P(),connectionAnalyticsId:A().max(1024).optional()}),rp=L({displayName:A().min(1).max(1024),hostname:A().min(1).max(1024),sshPort:M().int().min(1).max(65535).nullable(),identity:A().max(4096).nullable()});z(`action`,[L({action:H(`session`),operation:ep}),L({action:H(`list`)}),L({action:H(`catalog`)}),L({action:H(`read-thread`),hostId:tp.refine(e=>e!==`local`),input:Pd}),L({action:H(`save`),draft:rp,previous:np.nullable()}),L({action:H(`remove`),previous:np}),L({action:H(`connect`),hostId:tp,enabled:P()}),L({action:H(`state`),hostId:tp}),L({action:H(`runtime`),hostId:tp}),L({action:H(`update`),hostId:tp.refine(e=>e!==`local`),version:Xf.shape.version})]),R([L({result:U}),L({error:L({code:M().int(),message:A()})})]),L({prompt:A().trim().min(1).max(2e3),cwd:A().max(4096).nullable()}),A().trim().min(1).max(60).nullable();let ip=A().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),ap=R([A(),I({en:A()}).catchall(A())]),op=I({title:ap.optional(),description:ap.optional(),icon:A().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:A().optional()});I({extensions:F(I({id:ip,name:A().min(1).max(214),version:A().min(1).max(128),format:H(`dsh`),supportedTargets:Dc([H(`web`)]),enabledTargets:F(H(`web`)).max(1),source:A().min(1).max(4096),projectUrl:A().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:A(),meta:op.optional(),loadError:A().optional()})),loadedIds:F(ip),safeMode:P(),storeError:A().optional()});let sp=A().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);I({spec:A().trim().min(1).max(4096),registry:sp.optional()}).strict(),I({id:ip,enabled:P()}).strict(),I({id:ip}).strict();let cp=A().regex(/^[a-zA-Z0-9_-]{1,64}$/u),lp=A().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),up=V([`relay`,`tailscale`,`lan`,`custom`]),dp=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],fp=V(dp);new Set(dp);let pp=V([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]);I({peers:F(I({peerId:cp,hostId:lp,name:A().min(1).max(120),color:fp.optional(),origin:A().min(1).max(2048),transportKind:up,encrypted:P(),enabled:P(),state:pp,latencyMs:M().int().nonnegative().optional(),version:A().max(128).optional(),platform:A().max(64).optional(),hostname:A().max(255).optional(),homeDir:A().max(4096).optional(),lastError:A().max(1e3).optional(),projectCount:M().int().nonnegative(),createdAt:A(),updatedAt:A()}))}),I({connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional(),name:A().trim().min(1).max(120).optional(),color:fp.optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),I({peerId:cp,name:A().trim().min(1).max(120).optional(),color:fp.nullable().optional(),connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional(),enabled:P().optional()}),I({peerId:cp}),I({removed:P()}),I({peerId:cp.optional(),connectionUrl:A().min(1).max(4096).optional(),origin:A().min(1).max(2048).optional(),token:A().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let mp=I({id:A().min(1).max(1024),name:A().min(1).max(512),path:A().min(1).max(8192)});I({ok:P(),latencyMs:M().int().nonnegative().optional(),origin:A().max(2048).optional(),transportKind:up.optional(),encrypted:P().optional(),version:A().max(128).optional(),platform:A().max(64).optional(),hostname:A().max(255).optional(),homeDir:A().max(4096).optional(),projectCount:M().int().nonnegative().optional(),projects:F(mp).optional(),error:A().max(1e3).optional()});let hp=I({id:A().min(1).max(1024),name:A().min(1).max(512),path:A().min(1).max(8192),threadIds:F(A().min(1).max(1024))}),gp=I({attachments:H(1).optional(),workspaceFiles:H(1).optional(),officePreview:H(1).optional()}),_p=I({version:A().max(128),platform:A().max(64),hostname:A().max(255),homeDir:A().max(4096).optional(),epoch:A().min(1).max(256),projects:F(hp),capabilities:gp.optional()});L({threadId:A().min(1).max(1024),scope:A().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u).optional(),requestId:A().min(1).max(256).optional(),mode:V([`queue`,`steer`]).optional(),expectedTurnId:A().min(1).max(1024).nullable().optional(),content:F(z(`type`,[L({type:H(`text`),text:A()}),L({type:H(`file`),receiptId:A().min(1).max(128)})])).min(1).max(64)});let vp=I({ok:H(!1),error:I({code:A(),message:A(),details:B(A(),_c()).optional()})});R([I({ok:H(!0),value:I({receiptId:A().min(1),file:I({attachmentId:A(),name:A(),bytes:M().int().nonnegative()})})}),vp]),R([I({ok:H(!0),value:I({accepted:H(!0)})}),vp]);let yp=I({name:A().min(1).max(512),path:A().min(1).max(8192),kind:H(`directory`)});I({peerId:cp,path:A().min(1).max(8192).optional()}),I({path:A().min(1).max(8192),parentPath:A().min(1).max(8192).nullable(),homeDir:A().min(1).max(8192).optional(),entries:F(yp)}),I({peerId:cp,parentPath:A().min(1).max(8192),name:A().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),I({path:A().min(1).max(8192),name:A().min(1).max(255)}),I({peerId:cp,path:A().min(1).max(8192),title:A().trim().min(1).max(255).optional()}),I({peerId:cp,workspaceId:A().min(1).max(1024),title:A().trim().min(1).max(255)}),I({peerId:cp,workspaceId:A().min(1).max(1024)}),I({workspaceId:A().min(1).max(1024).optional(),manifest:_p}),H(1);function bp(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
123
114
  /* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
124
- if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let vd={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
125
- `,r:`\r`,t:` `},yd=/[\\\u0000-\u001f]/u;function bd(e){return e===` `||e===`
126
- `||e===`\r`||e===` `}function xd(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(yd),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++)xd(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=vd[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&&yd.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(bd(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(bd(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(bd(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(bd(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(bd(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(bd(e))return;this.fail();return;
115
+ if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let xp={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
116
+ `,r:`\r`,t:` `},Sp=/[\\\u0000-\u001f]/u;function Cp(e){return e===` `||e===`
117
+ `||e===`\r`||e===` `}function wp(e){return e>=`0`&&e<=`9`||e>=`a`&&e<=`f`||e>=`A`&&e<=`F`}(class e{static EMPTY=e.fromObject({});static fromText(t){let n=new e;return n.append(t),n.sealed=!0,n}static fromObject(t){let n=new e;return n.object=typeof t==`object`&&t&&!Array.isArray(t)?t:{},n.sealed=!0,n}chunks=[];object;sealed=!1;#e=[];#t=0;#n=0;#r=`root`;#i=!1;#a=0;#o=!1;#s=``;#c=null;#l=[];#u=!1;#d;#f=!1;#p=/* @__PURE__ */ new Map;#m=[];#h=/* @__PURE__ */ new Map;get isSealed(){return this.sealed}get invalid(){return this.scan(),this.#r===`invalid`||this.#f}append(e){if(this.sealed)throw Error(`PartialArguments: cannot append to a sealed view`);e.length!==0&&(this.chunks.push(e),this.#t+=e.length,this.#e.push(this.#t))}settle(t){if(this.object!==void 0||t.length!==this.#t)return e.fromText(t);let n=0;for(let r of this.chunks){if(!t.startsWith(r,n))return e.fromText(t);n+=r.length}return this.chunks=t.length===0?[]:[t],this.#e=t.length===0?[]:[t.length],this.sealed=!0,this}refresh(){if(this.#h.size===0)return!1;this.scan();let e=!1,t=!1;for(let n of this.#h.values())n.completion?t=!0:e=this.refreshRead(n)||e;if(t)for(let t of this.#h.values())t.completion&&(e=this.refreshRead(t)||e);return this.sealed&&this.#h.clear(),e}refreshRead(e){let t=e.answer();return!Object.is(t,e.last)&&(e.last=t,!0)}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),e=>e.length)}has(e){return this.remember(`has`,e,()=>this.hasNow(e))}complete(e){return this.remember(`complete`,e,()=>this.completeNow(e))}stringLength(e,t){let n=Math.max(1,Math.floor(t?.step??1)),r=t?.offset??0;return this.remember(`length:${n}:${r}`,e,()=>this.lengthNow(e),e=>e===void 0?void 0:Math.ceil((e+r)/n))}stringExceeds(e,t){let n=Math.max(0,Math.floor(t));return this.remember(`exceeds:${n}`,e,()=>(this.lengthNow(e,n+1)??0)>n)}text(e){return this.remember(`text`,e,()=>this.textNow(e))}textPrefix(e,t){let n=Math.max(1,Math.floor(t));return this.remember(`prefix:${n}`,e,()=>this.textPrefixNow(e,n))}value(e){return this.remember(`value`,e,()=>this.valueNow(e))}remember(e,t,n,r){this.scan();let i=n();if(!this.sealed){let a=`${e}/${t}`;this.#h.has(a)||this.#h.set(a,{completion:e===`complete`,answer:r===void 0?n:()=>r(n()),last:r===void 0?i:r(i)})}return i}closedNow(){return this.sealed||this.#r===`closed`||this.#r===`invalid`}keysNow(){return this.object===void 0?this.#m:Object.keys(this.object)}hasNow(e){return this.object===void 0?this.#p.has(e):Object.hasOwn(this.object,e)}completeNow(e){if(this.object!==void 0)return Object.hasOwn(this.object,e);let t=this.#p.get(e);return t!==void 0&&t.end>=0&&(t.kind===`string`?t.invalidAt===void 0:!t.invalid)}lengthNow(e,t=1/0){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t.length:void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;if(n.text!==void 0&&n.text.at===n.end)return n.text.length;let r=n.length??={at:n.start,length:0,text:``};return this.readString(n,r,t,!1),r.length}textNow(e){if(this.object!==void 0){let t=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof t==`string`?t:void 0}let t=this.#p.get(e);if(t?.kind!==`string`)return;if(t.text===void 0&&t.end>=0&&t.needsDecoding&&t.invalidAt===void 0){let e;try{e=JSON.parse(`"${this.slice(t.start,t.end)}"`)}catch{}e!==void 0&&(t.text={at:t.end,length:e.length,text:e})}let n=t.text??={at:t.start,length:0,text:``};return this.readString(t,n,1/0,!0),n.text}textPrefixNow(e,t){if(this.object!==void 0){let n=Object.hasOwn(this.object,e)?this.object[e]:void 0;return typeof n==`string`?n.slice(0,t):void 0}let n=this.#p.get(e);if(n?.kind!==`string`)return;let r=n.prefixes??=/* @__PURE__ */ new Map,i=r.get(t);return i===void 0&&(i={at:n.start,length:0,text:``},r.set(t,i)),this.readString(n,i,t,!0),i.text}valueNow(e){if(this.object!==void 0){if(!Object.hasOwn(this.object,e))return;let t=this.object[e];return typeof t==`string`?void 0:t}let t=this.#p.get(e);if(!(t?.kind!==`value`||t.end<0||t.invalid)){if(t.parsed===void 0)try{t.parsed=JSON.parse(this.slice(t.start,t.end))}catch{t.invalid=!0,this.#f=!0}return t.parsed}}chunkAt(e){let t=0,n=this.#e.length;for(;t<n;){let r=t+n>>>1;this.#e[r]<=e?t=r+1:n=r}return t}slice(e,t){if(e>=t)return``;let n=this.chunkAt(e),r=this.chunkAt(t-1),i=n===0?0:this.#e[n-1];if(n===r)return this.chunks[n].slice(e-i,t-i);let a=[this.chunks[n].slice(e-i)];for(let e=n+1;e<r;e++)a.push(this.chunks[e]);return a.push(this.chunks[r].slice(0,t-this.#e[r-1])),a.join(``)}readString(e,t,n,r){let i=Math.min(e.end<0?this.#n:e.end,e.invalidAt??1/0,this.#d??1/0);if(!e.needsDecoding){let e=Math.min(i-t.at,n-t.length);if(e<=0)return;r&&(t.text+=this.slice(t.at,t.at+e)),t.at+=e,t.length+=e;return}let a=this.chunkAt(t.at);for(;t.at<i&&t.length<n;){let o=a===0?0:this.#e[a-1],s=this.chunks[a],c=s.slice(t.at-o,Math.min(s.length,i-o)),l=c.search(Sp),u=Math.min(l<0?c.length:l,n-t.length);if(u>0){r&&(t.text+=c.slice(0,u)),t.at+=u,t.length+=u,t.at===o+s.length&&a++;continue}let d=c.length>1?c[1]:t.at+1<i?this.chunks[a+1][0]:void 0,f,p=2;if(c[0]===`\\`&&d===void 0&&e.end<0)return;if(c[0]===`\\`&&d===`u`){let n=this.slice(t.at+2,Math.min(i,t.at+6)),r=!0;for(let e=0;e<n.length;e++)wp(n[e])||(r=!1);if(r){if(n.length<4&&e.end<0)return;n.length===4&&(f=String.fromCharCode(Number.parseInt(n,16)))}p=6}else c[0]===`\\`&&d!==void 0&&(f=xp[d]);if(f===void 0){e.invalidAt=t.at,this.#f=!0;return}for(r&&(t.text+=f),t.length++,t.at+=p;a<this.chunks.length&&t.at>=this.#e[a];)a++}}scan(){if(this.object===void 0&&this.#n!==this.#t)for(let e=this.chunkAt(this.#n);e<this.chunks.length&&this.#d===void 0;e++){let t=this.chunks[e],n=e===0?0:this.#e[e-1];for(let e=this.#n-n;e<t.length&&this.#r!==`invalid`;e++){if(this.#r===`string`||this.#r===`nested`&&this.#u){let n=this.stringBoundary(t,e);if(this.#n+=n-e,e=n,e===t.length)break}this.step(t[e],this.#n),this.#n++}}}stringBoundary(e,t){let n=t;for(;;){let t=e.indexOf(`"`,n),r=t<0?e.length:t;if(this.#r===`string`){let t=this.#c;!t.needsDecoding&&Sp.test(e.slice(n,r))&&(t.needsDecoding=!0)}let i=r;for(;i>n&&e[i-1]===`\\`;)i--;let a=(r-i)%2==1!==(i===n&&this.#i);if(this.#i=t<0&&a,t<0||!a)return r;n=t+1}}step(e,t){switch(this.#r){case`root`:if(Cp(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(Cp(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(Cp(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(Cp(e))return;if(e===`:`){this.#r=`value`;return}this.fail();return;case`value`:this.beginValue(e,t);return;case`string`:{let e=this.#c;e.end=t,this.#c=null,this.#r=`comma-or-end`;return}case`scalar`:this.stepScalar(e,t);return;case`nested`:this.stepNested(e,t);return;case`comma-or-end`:if(Cp(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(Cp(e))return;this.fail();return;
127
118
  /* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
128
119
  case`invalid`:return;
129
120
  /* v8 ignore next 2 -- Every scanner mode has a handler above. */
130
- default:Sd(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){bd(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===`}`||bd(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 Sd(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function Cd(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 wd(e){return Object.getPrototypeOf(e)===null&&Cd(e,`Object`)}function Td(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Cd(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&wd(n)}function Ed(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&wd(t)}function Dd(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function Od(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(!Td(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(!Ed(r))return;let o=Dd(r);if(o===void 0)return;let s=t?{}:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o.length-1;e>=0;e--){let t=o[e];
121
+ default:Tp(this.#r)}}fail(){this.#d=this.#n,this.#r=`invalid`,this.#c=null}beginKey(e){this.#r=`key`,this.#a=e+1,this.#o=!1,this.#i=!1}stepKey(e,t){if(e<` `){this.fail();return}if(this.#i){this.#i=!1;return}if(e===`\\`){this.#i=!0,this.#o=!0;return}if(e!==`"`)return;let n=this.slice(this.#a,t);if(this.#o)try{this.#s=JSON.parse(`"${n}"`)}catch{this.fail();return}else this.#s=n;this.#r=`colon`}open(e){this.#p.has(this.#s)||this.#m.push(this.#s),this.#p.set(this.#s,e),this.#c=e}beginValue(e,t){Cp(e)||(e===`"`?(this.open({kind:`string`,start:t+1,end:-1,needsDecoding:!1,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0}),this.#i=!1,this.#r=`string`):e===`}`||e===`,`||e===`:`||e===`]`?this.fail():(this.open({kind:`value`,start:t,end:-1,parsed:void 0,invalid:!1}),e===`{`||e===`[`?(this.#r=`nested`,this.#l=[e===`{`?`}`:`]`],this.#u=!1,this.#i=!1):this.#r=`scalar`))}stepScalar(e,t){(e===`,`||e===`}`||Cp(e))&&(this.closeValue(t),this.#r=e===`,`?`key-only`:e===`}`?`closed`:`comma-or-end`)}stepNested(e,t){if(this.#u)this.#u=!1;else if(e===`"`)this.#u=!0;else if(e===`{`||e===`[`)this.#l.push(e===`{`?`}`:`]`);else if(e===`}`||e===`]`){if(this.#l.pop()!==e){this.fail();return}this.#l.length===0&&(this.closeValue(t+1),this.#r=`comma-or-end`)}}closeValue(e){let t=this.#c;t.end=e,this.#c=null}});function Tp(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function Ep(e,t){let n=Object.getOwnPropertyDescriptor(e,`constructor`)?.value;if(typeof n!=`function`)return!1;try{return n.name===t&&n.prototype===e&&Function.prototype.toString.call(n)===Function.prototype.toString.call(t===`Array`?Array:Object)}catch{return!1}}function Dp(e){return Object.getPrototypeOf(e)===null&&Ep(e,`Object`)}function Op(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!Ep(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&Dp(n)}function kp(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&Dp(t)}function Ap(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function jp(e,t){let n=/* @__PURE__ */ new Set,r,i=(e,t)=>{e!==void 0&&(e.kind===`root`?r=t:e.kind===`array`?e.target[e.index]=t:Object.defineProperty(e.target,e.key,{value:t,enumerable:!0,configurable:!0,writable:!0}))},a=[{kind:`visit`,value:e,...t?{destination:{kind:`root`}}:{}}];for(let e=a.pop();e!==void 0;e=a.pop()){if(e.kind===`leave`){n.delete(e.source);continue}if(e.kind===`array-item`){if(!Object.prototype.hasOwnProperty.call(e.source,e.index))return;a.push({kind:`visit`,value:e.source[e.index],...e.target===void 0?{}:{destination:{kind:`array`,target:e.target,index:e.index}}});continue}if(e.kind===`object-property`){a.push({kind:`visit`,value:e.source[e.key],...e.target===void 0?{}:{destination:{kind:`object`,target:e.target,key:e.key}}});continue}let r=e.value;if(r===null){i(e.destination,null);continue}if(typeof r==`boolean`||typeof r==`string`){i(e.destination,r);continue}if(typeof r==`number`){if(!Number.isFinite(r)||Object.is(r,-0))return;i(e.destination,r);continue}if(typeof r!=`object`||n.has(r))return;if(Array.isArray(r)){if(!Op(r))return;let o=r.length;if(Reflect.ownKeys(r).length!==o+1)return;let s=t?[]:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o-1;e>=0;e--)a.push({kind:`array-item`,source:r,index:e,...s===void 0?{}:{target:s}});continue}if(!kp(r))return;let o=Ap(r);if(o===void 0)return;let s=t?{}:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o.length-1;e>=0;e--){let t=o[e];
131
122
  /* v8 ignore next -- the loop is bounded by the captured key count. */
132
- if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function kd(e){return Od(e,!0)}function Ad(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
123
+ if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function Mp(e){return jp(e,!0)}function Np(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
133
124
  /* v8 ignore next -- the loop condition guarantees one pending task. */
134
125
  if(e===void 0)continue;if(e.kind===`property`){n.push({kind:`visit`,node:e.source[e.key]});continue}let r=e.node;if(typeof r!=`object`||!r||r instanceof AbortSignal||t.has(r))continue;t.add(r),Object.freeze(r);let i=Object.keys(r);for(let e=i.length-1;e>=0;e--){let t=i[e];
135
126
  /* v8 ignore next -- the loop is bounded by the captured key count. */
136
- t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function jd(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]`))}},Nd=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}},Pd=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 Fd(){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 Id(e){return{kind:`leaf`,entries:e,length:e.length}}function Ld(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Rd(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 zd(e,t,n,r){let i;return{get entries(){return i??=Rd(e),i},hasMore:t,revision:n,change:r}}var Bd=class{listeners=/* @__PURE__ */ new Set;window=Id([]);snapshot=zd(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=Id(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Ld(Id(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Ld(this.window,Id(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Rd(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=Id(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=zd(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Vd(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Hd(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Ud(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 Wd(e){let t=kd(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Gd(e){let t=[];for(let n of e){let e=Kd(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 Kd(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`:{Yd(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Jd(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return qd(t,e.length,t.type),t}case`tool-call-chunks`:{Yd(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Jd(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 qd(t,e.length,t.type),t}case`chunk`:{Yd(t,[`type`,`time`,`chunk`],`chunk`);let e=Hd(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=Wd(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Ad({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function qd(e,t,n){if(Hd(e.time0),Ud(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 Jd(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Yd(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 Xd=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 Gd(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=Zd(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function Zd(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Qd(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let $d={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},ef={...$d,turnWindow:{...$d.turnWindow,minMessages:200}};var tf=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 Xd;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 Bd;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Pd(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Nd,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=Fd(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}activeTurnForSteering(){let e=this.projections.get(uu);return typeof e==`string`?e:null}async prompt(e,t,n,r){let i=r??Fd();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=Vd(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Vd()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}return!s.ok&&s.error.code===`remote/outcome-unknown`&&this.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(this.acceptPrompt(),s):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:s.error,requestId:i},this.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i)}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...$d})}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,...ef}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=ee(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:this.toolOutputs.values,entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(du),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open($d),e!==this.openGeneration||this.events!==n)return;this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:Qd(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=ee(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,du),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:ee(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:ee(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:rf(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=rf(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,rf(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,nf(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){let n=this.submissionSettlements.get(e);
127
+ t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function Pp(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.sessionId,n);let n=/* @__PURE__ */ new Map,r=[];for(let i of e)if(i.parentSessionId!==void 0&&t.has(i.parentSessionId)){let e=n.get(i.parentSessionId)??[];e.push(i),n.set(i.parentSessionId,e)}else r.push(i);let i=[],a=/* @__PURE__ */ new Set,o=(e,t)=>{if(a.has(e.sessionId)){console.warn(`[session-controller] lineage cycle at ${e.sessionId}; emitting as root`);return}a.add(e.sessionId);let{agentAvailable:r,...s}=e;i.push({...s,depth:t});let c=n.get(e.sessionId);if(c!==void 0)for(let e of c)o(e,t+1)};for(let e of r)o(e,0);for(let t of e)a.has(t.sessionId)||o(t,0);return i}var Fp=class{rebuild;listeners=/* @__PURE__ */ new Set;dirty=!1;notifyPending=!1;scheduled=`none`;scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!==`microtask`&&this.schedule(`microtask`)}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled===`none`&&this.schedule(typeof globalThis.requestAnimationFrame==`function`?`frame`:`microtask`)}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}},Ip=class{rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;anyNotifier=new Fp(()=>{});faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){let r=this.rows.get(e);r?.kind===`sequenced`&&n<=r.seq||(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e))}applyLive(e,t,n){let r=this.rows.get(e);r?.kind===`sequenced`&&n<r.seq||(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e))}applyCached(e){for(let t of Object.keys(e))this.rows.get(t)?.kind!==`sequenced`&&(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t))}seed(e,t,n){for(let[e,t]of this.rows)t.kind===`cached`&&(this.rows.delete(e),this.changed(e));let r=e.values;for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new Fp(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}},Lp=class{readRemote;values;pending=/* @__PURE__ */ new Map;constructor(e,t){this.readRemote=e,this.values=new Map(t)}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.values.set(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}};function Rp(){let e=globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)),t=Array.from(e,(e,t)=>(t===6?e&15|64:t===8?e&63|128:e).toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function zp(e){return{kind:`leaf`,entries:e,length:e.length}}function Bp(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Vp(e){if(e.kind===`leaf`)return e.entries;let t=Array(e.length),n=[e],r=0;for(;n.length>0;){let e=n.pop();if(e.kind===`concat`)n.push(e.right,e.left);else for(let n of e.entries)t[r]=n,r+=1}return t}function Hp(e,t,n,r){let i;return{get entries(){return i??=Vp(e),i},hasMore:t,revision:n,change:r}}var Up=class{listeners=/* @__PURE__ */ new Set;window=zp([]);snapshot=Hp(this.window,!1,0,{kind:`replace`,entries:[]});getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=zp(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Bp(zp(e),this.window),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Bp(this.window,zp(t)),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Vp(this.window).filter(t=>t.type!==`transient`||t.event.data.attemptId!==e);if(t!==void 0){let e=n.findIndex(e=>e.event.seq>t.event.seq);e<0?n.push(t):n.splice(e,0,t)}this.window=zp(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Hp(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Wp(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Gp(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Kp(e,t){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`${t} index must be a non-negative safe integer`);return e}function qp(e){let t=Mp(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Jp(e){let t=[];for(let n of e){let e=Yp(n);if(e.type===`chunk`){t.push({time:e.time,chunk:e.chunk});continue}let r=e.type===`tool-call-chunks`?e.args:e.texts,i=e.time0;for(let n=0;n<r.length;n+=1){n>0&&(i+=e.dt[n-1]);let a;a=e.type===`text-chunks`?{type:`text-delta`,index:e.index,text:r[n]}:e.type===`reasoning-chunks`?{type:`reasoning-delta`,index:e.index,text:r[n]}:{type:`tool-call-delta`,index:e.index,id:e.id,...Object.hasOwn(e,`name`)?{name:e.name}:{},argumentsDelta:r[n]},t.push({time:i,chunk:a})}}return t}function Yp(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`Assistant stream record must be an object`);let t=e;switch(t.type){case`text-chunks`:case`reasoning-chunks`:{Qp(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Zp(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Xp(t,e.length,t.type),t}case`tool-call-chunks`:{Qp(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Zp(t.args,`tool-call-chunks args`);if(e.length===0)throw TypeError(`tool-call-chunks args must be non-empty`);if(typeof t.id!=`string`||t.id.length===0)throw TypeError(`tool-call-chunks id must be a non-empty string`);if(t.name!==void 0&&(typeof t.name!=`string`||t.name.length===0))throw TypeError(`tool-call-chunks name must be a non-empty string`);return Xp(t,e.length,t.type),t}case`chunk`:{Qp(t,[`type`,`time`,`chunk`],`chunk`);let e=Gp(t.time);if(typeof t.chunk!=`object`||t.chunk===null||Array.isArray(t.chunk))throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`);let n;try{n=qp(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Np({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Xp(e,t,n){if(Gp(e.time0),Kp(e.index,n),!Array.isArray(e.dt)||e.dt.some(e=>!Number.isSafeInteger(e)))throw TypeError(`${n} dt must contain safe integers`);if(e.dt.length!==t-1)throw TypeError(`${n} dt length must be one less than its members`);let r=e.time0;for(let t of e.dt)if(r+=t,!Number.isSafeInteger(r))throw TypeError(`${n} member times must stay safe integers`)}function Zp(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Qp(e,t,n){if(Object.keys(e).length!==t.length||!t.every(t=>Object.hasOwn(e,t)))throw TypeError(`${n} Assistant stream record must contain exactly ${t.join(`, `)}`)}var $p=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Jp(n.stream).entries())if(r.push(this.transientEntry(n,t.time,t.chunk)),e+1>=n.nextIndex)break}return r}acceptDurable(e){let t=e.event;this.durableCursor=Math.max(this.durableCursor,t.seq),this.transientInGap=0;let n=em(e);if(n!==void 0&&this.attemptForSettlement(n.event)!==void 0){if(this.pending.has(t.seq))return{type:`rebaseline`};this.pending.set(t.seq,n)}else return this.publish(e)}acceptFrame(e){switch(e.type){case`start`:if(this.activeAttempt!==void 0||this.retainedAttempt!==void 0||this.pending.size>0)return{type:`rebaseline`};this.pending.clear(),this.activeAttempt={attemptId:e.attemptId,startedAfterSeq:e.startedAfterSeq,turn:e.turn,step:e.step,nextIndex:0};return;case`chunk`:{let t=this.activeAttempt;return t===void 0||t.attemptId!==e.attemptId?void 0:e.index===t.nextIndex?(t.nextIndex+=1,{type:`transient`,entry:this.transientEntry(t,e.time,e.chunk)}):{type:`rebaseline`}}case`end`:{let t=this.activeAttempt;if(t===void 0||t.attemptId!==e.attemptId)return;if(this.activeAttempt=void 0,e.index!==t.nextIndex)return{type:`rebaseline`};if(e.outcome.kind===`abandoned`)return this.pending.size===0?{type:`abandonment`,attemptId:t.attemptId}:{type:`rebaseline`};if(this.publishedSeqs.has(e.outcome.seq))return;let n=this.pending.get(e.outcome.seq);return n===void 0||n.event.type!==e.outcome.eventType?{type:`rebaseline`}:(this.pending.delete(e.outcome.seq),n.event.type===`assistant/message`&&n.event.data.interrupted!==!0?(this.retainedAttempt={attemptId:t.attemptId,turn:t.turn,step:t.step},this.publish(n)):(this.publishedSeqs.add(n.event.seq),{type:`settlement`,attemptId:t.attemptId,entry:n}))}}}transientEntry({attemptId:e,turn:t,step:n},r,i){let a=this.durableCursor+1;this.transientInGap+=1;let o=Math.max(1/(this.transientInGap+1),a*2**-52);return{type:`transient`,event:{type:`assistant/live-chunk`,seq:Math.max(this.durableCursor,a-o),order:++this.transientOrder,time:r,data:{attemptId:e,turn:t,step:n,chunk:i}}}}attemptForSettlement(e){let t=this.activeAttempt;if(!(t===void 0||e.type===`assistant/message`&&e.surfaceOp!==`append`||e.seq<=t.startedAfterSeq||t.turn!==e.data.turn||t.step!==e.data.step))return t}publish(e){this.publishedSeqs.add(e.event.seq);let t=this.retainedAttempt;return t!==void 0&&e.event.type===`step/end`&&e.event.data.turn===t.turn&&e.event.data.step===t.step?(this.retainedAttempt=void 0,{type:`publish`,entry:e,retireAttemptId:t.attemptId}):{type:`publish`,entry:e}}};function em(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function tm(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let nm={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},rm={...nm,turnWindow:{...nm.turnWindow,minMessages:200}};var im=class{sessionId;remote;baseSeq=m(0);cachedJournal;toolOutputs;hasMore=!1;openState=`cold`;lastSyncedAt;openError=null;openPromise=null;openGeneration=0;loadingOlder=!1;olderError=null;jumpTargetSeq=null;jumpPromise=null;pendingHistory=null;stopObservingInbox;onEngaged;assistantStream=new $p;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Up;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Lp(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new Ip,n.cachedView){let e=n.cachedView;this.cachedJournal=e.journal,this.baseSeq=e.baseSeq,this.hasMore=e.hasMore,this.lastSyncedAt=e.lastSyncedAt,this.projections.applyCached(e.projections),this.eventSource.replace(e.entries,e.hasMore)}this.address=n.address,this.parentAvailable=n.parentAvailable,this.notifier=new Fp(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){let t=Rp(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onRetire:e.onRetire,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}activeTurnForSteering(){let e=this.projections.get(ff);return typeof e==`string`?e:null}async prompt(e,t,n,r){let i=r??Rp();this.promptError=null,this.lastAgentError=null,this.promptAttempted=!0,this.blankBit&&(this.firstPromptPendingTurn=!0),this.notifier.markDirty();let a={observed:!1};this.inFlightPrompts.set(i,a);try{let a=this.submissionSettlements.get(i),s;if(t===`steer`&&r!==void 0&&a===void 0)s={ok:!1,error:new o(`remote/turn-changed`,`The selected Turn has ended or changed.`,{})};else if(this.address===void 0){let r=Wp(),o=this.projections.get(`remoteHost`)!=null,c=a?a.placement===`transcript`:!this.running;s=await this.remote.session.prompt({requestId:i,sessionId:this.sessionId,mode:t,...o&&t===`queue`&&c?{sendWhenIdle:!0}:{},...t===`steer`?{expectedTurnId:a?a.expectedTurnId:this.activeTurnForSteering()}:{},content:e,clientTimeZone:r},n)}else if(e.some(e=>e.type===`file`))s={ok:!1,error:new o(`subagent/attachment-invalid`,`subagent continuation does not accept files`,{reason:`SUBAGENT_FILE_UNSUPPORTED`})};else{let r=e,a=await this.remote.subagents.prompt({requestId:i,parentSessionId:this.address.parentSessionId,childSessionId:this.address.childSessionId,mode:`continuable`,delivery:t,content:r,clientTimeZone:Wp()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}return!s.ok&&s.error.code===`remote/outcome-unknown`&&this.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(this.acceptPrompt(),s):(r!==void 0&&this.retireFailedSubmission(r),this.promptError={op:`send`,error:s.error,requestId:i},this.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i)}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...nm})}catch(e){t===this.openGeneration&&(this.olderError=(0,i.isRemoteFailure)(e)?e:new o(`gateway/internal`,`Could not load earlier history.`,{}))}finally{t===this.openGeneration&&(this.loadingOlder=!1,this.notifier.markDirty())}}loadThrough(e){if(this.openState!==`open`||!this.hasMore||this.baseSeq<=e)return Promise.resolve();if(this.jumpPromise!==null)return this.jumpTargetSeq=p(Math.min(this.jumpTargetSeq??e,e)),this.jumpPromise;if(this.loadingOlder)return Promise.resolve();let t=this.events;if(t===void 0)return Promise.resolve();let n={beforeSeq:this.baseSeq,hasMore:this.hasMore,pages:[]};this.pendingHistory=n,this.jumpTargetSeq=e,this.olderError=null,this.loadingOlder=!0,this.notifier.markDirty();let r=this.openGeneration;return this.jumpPromise=(async()=>{try{for(;n.hasMore&&this.jumpTargetSeq!==null&&n.beforeSeq>this.jumpTargetSeq;){if(r!==this.openGeneration)return;let e=n.beforeSeq;if(await t.prepend({beforeSeq:e,...rm}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:this.toolOutputs.values,entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(pf),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(nm),e!==this.openGeneration||this.events!==n)return;this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:tm(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq))}this.lastSyncedAt=Date.now(),this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=m(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,pf),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event),this.notifier.markDirty();else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId),this.notifier.markDirty();else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),(t||e.retireAttemptId!==void 0)&&this.notifier.markDirty()}else e?.type===`transient`&&(this.eventSource.append(e.entry),this.notifier.markDirty())}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e)}else{this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t);for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:om(a.content)})}}observeSubmissionMessage(e,t,n){let r=e.source;if(r.kind!==`user`||!(`rpcId`in r))return;this.confirmPrompt(r.rpcId);let i=this.submissionSettlements.get(r.rpcId);i===void 0||i.retiring||(t?(i.admitted=om(e.content),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,om(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,am(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){let n=this.submissionSettlements.get(e);
137
128
  /* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
138
- n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function nf(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function rf(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 af=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 of(e){return e===-1?-1:p(e)}let sf=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]);var cf=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new af;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;listRequestWorkspaceId;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];notifier=new 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(du)}return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.listMutations=null,this.listInflight=null,this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new tf(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 Nd;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:of(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){return this.nextCursor?this.refreshList(this.nextCursor,e):Promise.resolve()}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let n=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0,this.listRequestWorkspaceId=e===void 0?void 0:t;let r=this.summaries,a=[];return this.listMutations=a,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==a)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...r.filter(e=>!o.has(e.sessionId)&&(s||!n&&t.has(e.sessionId)))],l=this.listPhase===`pending`?c:_d(r,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of a)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=a.reduce(lf,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===a&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==a)return;this.listState=`error`,this.listError=e}finally{this.listMutations===a&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=uf(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:uf(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=lf(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=of(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,du)}this.notifier.markDirty()}handleSessionAdded(e,t=!0){t&&this.summaryOnlyIds.delete(e.sessionId),this.mergeSummary(e),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let n=this.sessions.get(e.sessionId);n?.handleRestored(),n?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=of(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:Sd(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(sf);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=jd(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);return e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e),{items:this.itemsCache,hasMore:!!this.nextCursor,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,errorWorkspaceId:this.listError&&this.listRequestIsMore?this.listRequestWorkspaceId??null:null,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([e,t])=>[e,{values:t.values(),state:`idle`,error:null,...this.projectionLoads.get(e)}]))}}};function lf(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 uf(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var df=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},ff=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 pf(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 mf(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 hf(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let gf=Object.freeze({referenceCount:0,retainedBy:hf({})});async function _f(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 vf=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]);_f(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()}},yf=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 cf(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}loadSummary(e){return this.manager.loadSummary(e)}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new df(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 ff(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,mf(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:hf({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new vf(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?gf:Object.freeze({referenceCount:r,retainedBy:hf(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??gf}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:gf,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,errorWorkspaceId:c,headRefreshRevision:l,summaryOnlyIds:u}=this.manager.getListSnapshot(),d=[],f={};for(let e of t)d.push(e.sessionId),f[e.sessionId]={id:e.sessionId,displayTitle:pf(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:this.retentionSnapshot(e.sessionId).retainedBy,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=f[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?f[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(f[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(f[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;f[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:d,byId:f,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,listErrorWorkspaceId:c,headRefreshRevision:l??0,summaryOnlyIds:u??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let bf=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function xf(e){let t=e.remote,n=e.get(`connection`),r=new yf(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=Bd,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=df,n.SessionEventStream=pe,n.SessionForkError=ff,n.apply=xf,n.createScope=_e,n.createSessionControlStream=fe,n.inject=bf,n.scopeOf=ve,t.exports}});
129
+ n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function am(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function om(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=n;(e.type===`image`||e.type===`file`)&&typeof e.attachment==`object`&&e.attachment!==null&&t.push(e.attachment)}return t}var sm=class{views=/* @__PURE__ */ new Map;take(e){let t=this.views.get(e);return this.views.delete(e),t}remember(e,t){if(this.views.delete(e),this.views.set(e,t),this.views.size<=8)return;let n=this.views.keys().next().value;return this.views.delete(n),n}delete(e){this.views.delete(e)}clear(){this.views.clear()}};function cm(e){return e===-1?-1:p(e)}let lm=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]);var um=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new sm;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;listRequestWorkspaceId;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];notifier=new Fp(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r){let t=this.recentViews.remember(e,r);t&&this.projectionStores.get(t)?.discard(pf)}return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.listMutations=null,this.listInflight=null,this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new im(e,this.remote,{...t===void 0?{}:{address:t,...n===void 0?{}:{parentAvailable:n}},onEngaged:e=>{!this.disposed&&this.retainedIds(this.summaries).has(e.sessionId)&&(this.engagedSessions.has(e.sessionId)||(this.engagedSessions.add(e.sessionId),this.recordMutation({kind:`engaged`,sessionId:e.sessionId})),this.sessions.get(e.sessionId)?.handleBlank(!1))},projections:this.projectionStore(e),cachedView:this.recentViews.take(e)})}effectiveBlank(e){return e.blank&&!this.engagedSessions.has(e.sessionId)}retainedIds(e){let t=new Set(e.map(e=>e.sessionId));for(let e of this.sessions.keys())t.add(e);for(let e of this.addresses.keys())t.add(e);return t}pruneEngagement(e,t){t.has(e)||this.engagedSessions.delete(e)}projectionStore(e){let t=this.projectionStores.get(e);if(t===void 0){t=new Ip;let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.values();this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.values()===a&&r.clear():r.seed({...t.value,asOfSeq:cm(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.nextCursor=void 0,this.listMutations=null,this.listInflight=null,this.refreshList())}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){return this.nextCursor?this.refreshList(this.nextCursor,e):Promise.resolve()}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null)return this.listInflight;let n=this.includeArchived;this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0,this.listRequestWorkspaceId=e===void 0?void 0:t;let r=this.summaries,a=[];return this.listMutations=a,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==a)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),o=new Set(i.value.items.map(e=>e.sessionId)),s=i.value.nextCursor!==void 0;(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=i.value.nextCursor??null);let c=[...i.value.items,...r.filter(e=>!o.has(e.sessionId)&&(s||!n&&t.has(e.sessionId)))],l=this.listPhase===`pending`?c:bp(r,c,e=>e.sessionId),u=/* @__PURE__ */ new Set;for(let e of a)e.kind===`remove`&&u.add(e.sessionId);for(let e of l)e.running&&!u.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let d=a.reduce(dm,l);this.summaries=d;let f=new Set(d.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(o.has(e)||!f.has(e))&&this.summaryOnlyIds.delete(e);let p=this.retainedIds(d);for(let e of this.engagedSessions)this.pruneEngagement(e,p);this.listState=`idle`,this.listPhase=`ready`,this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===a&&(this.headRefreshRevision+=1)}else this.listState=`error`,this.listError=i.error}catch(e){if(!(0,i.isRemoteFailure)(e))throw e;if(this.listMutations!==a)return;this.listState=`error`,this.listError=e}finally{this.listMutations===a&&(this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t=e.sessionId===void 0?{}:{sessionId:e.sessionId},n=e.workspaceId===void 0?{...e.cwd===void 0?{}:{cwd:e.cwd},...t}:{workspaceId:e.workspaceId,...t},r=await this.remote.session.create(n);if(r.ok)this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:r.value.sessionId,updatedAt:Date.now(),running:!1,blank:!0,...e.cwd===void 0?{}:{cwd:e.cwd}}});else{let e=fm(r.error);e!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:e,updatedAt:Date.now(),running:!1,blank:!0}})}return r}async fork(e){let t=this.sessions.get(e.sessionId);if(t&&t.getSnapshot().openState!==`open`)return{ok:!1,error:new o(`session/syncing`,`Wait for the Session history to finish synchronizing.`,{})};let n=this.summaries.find(t=>t.sessionId===e.sessionId),r=await this.remote.session.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:e.atSeq}}),i=r.ok?r.value.sessionId:fm(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq)),n}mergeSummary(e){this.recordMutation({kind:`upsert`,summary:e}),this.updateParentAvailability()}recordMutation(e){this.disposed||(this.listMutations?.push(e),this.summaries=dm(this.summaries,e),this.notifier.markDirty())}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):(this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq)),this.notifier.markDirty())}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=cm(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,pf)}this.notifier.markDirty()}handleSessionAdded(e,t=!0){t&&this.summaryOnlyIds.delete(e.sessionId),this.mergeSummary(e),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let n=this.sessions.get(e.sessionId);n?.handleRestored(),n?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=cm(t.asOfSeq);for(let[r,i]of Object.entries(t.values))n.apply(r,i,e);return}case`cached`:n.applyCached(t.values);return;default:Tp(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){this.summaryOnlyIds.delete(e);let t=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`);this.recordMutation(t?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e}),t?this.sessions.get(e)?.handleRunning(!1):(this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved());let n=this.projectionStores.get(e)?.values().subagentCatalog;!t&&(n===void 0||n.length===0)&&this.projectionStores.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e),this.projectionLoads.delete(e);for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e),this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0}),this.updateParentAvailability(),this.sessions.get(e)?.handleRunning(t)}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t})}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(lm);this.listMutations=null,this.listInflight=null,this.nextCursor=void 0,this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=Pp(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);return e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e),{items:this.itemsCache,hasMore:!!this.nextCursor,headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,errorWorkspaceId:this.listError&&this.listRequestIsMore?this.listRequestWorkspaceId??null:null,projectionsBySession:Object.fromEntries([...this.projectionStores].map(([e,t])=>[e,{values:t.values(),state:`idle`,error:null,...this.projectionLoads.get(e)}]))}}};function dm(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.find(e=>e.sessionId===t.summary.sessionId);if(n===void 0)return[t.summary,...e];let r={...n,blank:n.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...n.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...n.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...n.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};return r.cwd===n.cwd&&r.parentSessionId===n.parentSessionId&&r.origin===n.origin&&r.blank===n.blank&&r.agentAvailable===n.agentAvailable&&r.running===n.running?[...e]:e.map(e=>e.sessionId===t.summary.sessionId?r:e)}case`remove`:return e.filter(e=>e.sessionId!==t.sessionId);case`status`:return e.map(e=>e.sessionId===t.sessionId&&(e.running!==t.running||e.agentAvailable!==t.agentAvailable||t.running&&e.blank)?{...e,running:t.running,agentAvailable:t.agentAvailable,blank:e.blank&&!t.running}:e);case`activity`:return e.map(e=>e.sessionId===t.sessionId&&t.updatedAt>e.updatedAt?{...e,updatedAt:t.updatedAt}:e);case`engaged`:return e.map(e=>e.sessionId===t.sessionId&&e.blank?{...e,blank:!1}:e)}}function fm(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var pm=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},mm=class extends Error{rpcError;sourceSessionId;name=`SessionForkError`;constructor(e,t){super(`session fork failed: ${e.code}: ${e.message}`),this.rpcError=e,this.sourceSessionId=t}};function hm(e,t,n){if(e!==void 0)return e;if(t!==void 0&&t!==``){let e=me(t);if(e!==``)return e}return n}function gm(e){let t=/^(.*?)\((\d+)\)$/u.exec(e);if(t?.[1]!==void 0&&t[2]!==void 0)return`${t[1]}(${BigInt(t[2])+1n})`;let n=/^(.*?)((\d+))$/u.exec(e);return n?.[1]!==void 0&&n[2]!==void 0?`${n[1]}(${BigInt(n[2])+1n})`:`${e} (1)`}function _m(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let vm=Object.freeze({referenceCount:0,retainedBy:_m({})});async function ym(e,t){if(t===void 0)return e;let n=Promise.withResolvers(),r=()=>{n.reject(t.reason)};t.addEventListener(`abort`,r,{once:!0});try{t.aborted&&r(),await Promise.race([e,n.promise])}finally{t.removeEventListener(`abort`,r)}}var bm=class{sessionId;record;releaseReference;released=new AbortController;readiness=Promise.withResolvers();ready=this.readiness.promise;constructor(e,t,n){this.sessionId=e,this.record=t,this.releaseReference=n,this.ready.catch(()=>{})}get binding(){if(this.record===void 0||!this.record.live)throw Error(`Session reference "${this.sessionId}" is released`);return this.record.binding}attachOpening(e,t){let n=t===void 0?this.released.signal:AbortSignal.any([this.released.signal,t]);ym(e,n).then(()=>{try{n.throwIfAborted(),this.readiness.resolve(this.binding)}catch(e){this.readiness.reject(e)}},e=>{this.readiness.reject(e)})}release(){let e=/* @__PURE__ */ Error(`Session reference "${this.sessionId}" is released`),t=this.releaseReference;this.released.abort(e),this.readiness.reject(e),this.record=void 0,this.releaseReference=void 0,t?.()}[Symbol.dispose](){this.release()}},xm=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new um(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}loadSummary(e){return this.manager.loadSummary(e)}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new pm(t.error,e.sessionId);return this.projectList(),t.value.sessionId}async fork(e){let t=e.increaseTitle?this.list.getSnapshot().byId[e.sessionId]?.title:void 0,n=await this.manager.fork({sessionId:e.sessionId,...e.atSeq===void 0?{}:{atSeq:p(e.atSeq)}});if(!n.ok)throw new mm(n.error,e.sessionId);this.projectList();let r=n.value.sessionId;if(e.onCreated?.(r),t!==void 0){let e=await this.manager.rename(r,gm(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:_m({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new bm(e,n,()=>{if(!n.live)return;let r=n.retention.referenceCount-1,{[t]:i=0,...a}=n.retention.retainedBy,o=i>1?{...a,[t]:i-1}:a;n.retention=r===0?vm:Object.freeze({referenceCount:r,retainedBy:_m(o)}),r===0?this.retireScope(e,n):this.publishRetention(e)});return this.list.getSnapshot().byId[e]===void 0&&this.manager.subagentAddress(e)!==void 0&&this.projectList(),this.publishRetention(e),i}retentionSnapshot(e){return this.scopes.get(e)?.retention??vm}publishRetention(e){let t=this.list.getSnapshot(),n=t.byId[e],r=this.retentionSnapshot(e).retainedBy;n!==void 0&&n.retainedBy!==r&&this.list.set({...t,byId:{...t.byId,[e]:{...n,retainedBy:r}}});let i=this.retainObservers.get(e),o=this.retentionSnapshot(e);i!==void 0&&i.published!==o&&(i.published=o,(0,a.notifySubscribers)(i.listeners,`[session-controller] reference sources`))}retireScope(e,t,n=!0){if(!t.live)return;t.live=!1,this.scopes.get(e)===t&&this.scopes.delete(e),t.session.unbindScope();let r=this.manager.drop(e,t.session);this.projectList(),this.publishRetention(e),this.startScopeDrop(e,t,n,r)}materializeScope(e){let{fiber:t,ctx:n}=_e(this.rootCtx,e),r=this.manager.get(e);r.bindScope(n);let i={fiber:t,ctx:n,binding:{sessionId:e,session:r,eventSource:r.eventSource,ctx:n},session:r,retention:vm,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,state:a,error:o,errorPage:s,errorWorkspaceId:c,headRefreshRevision:l,summaryOnlyIds:u}=this.manager.getListSnapshot(),d=[],f={};for(let e of t)d.push(e.sessionId),f[e.sessionId]={id:e.sessionId,displayTitle:hm(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:this.retentionSnapshot(e.sessionId).retainedBy,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};for(let[e,t]of Object.entries(r))for(let n of t.values.subagentCatalog??[]){let t=n.id,r=f[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?f[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(f[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}for(let[t,n]of this.scopes){if(f[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;f[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:d,byId:f,phase:n,projectionsBySession:r,hasMore:i,loading:a===`loading`,listError:o?.message??null,listErrorPage:s,listErrorWorkspaceId:c,headRefreshRevision:l??0,summaryOnlyIds:u??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let Sm=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function Cm(e){let t=e.remote,n=e.get(`connection`),r=new xm(e,t);e.remote.$on(`api-session/added`,e=>{r.handleSessionAdded(e)}),e.remote.$on(`api-session/removed`,e=>{r.handleSessionRemoved(e)}),e.remote.$on(`api-session/status`,(e,t)=>{r.handleSessionStatus(e,t)}),e.remote.$on(`api-session/activity`,(e,t)=>{r.handleSessionActivity(e,t)}),e.remote.$on(`api-session/error`,(e,t)=>{r.handleSessionError(e,t)});let i,a=()=>{if(n.generation.getSnapshot()===void 0)return;let e=i;i=void 0,e?.dispose(),r.handleConnected();let a=fe(t,{accept:e=>{i===a&&r.handleControlFrame(e)},failed:e=>{i===a&&console.error(`[session-controller] control stream failed:`,e)}});i=a,a.start()};e.effect(()=>n.generation.subscribe(a),`session-controller.client.generation`),a(),e.typert.contexts.registerClient(`agent`,{identity:e=>r.sessionOf(e)?.sessionId,resolve:e=>{let t=r.retainAgentScope(e);return c(t.binding.ctx,()=>{t.release()})}}),e.effect(()=>async()=>{await i?.dispose()},`session-controller.client.control`)}return n.MutableSessionEventSource=Up,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=pm,n.SessionEventStream=pe,n.SessionForkError=mm,n.apply=Cm,n.createScope=_e,n.createSessionControlStream=fe,n.inject=Sm,n.scopeOf=ve,t.exports}});