@codexhost/cli-win32-x64 0.34.0 → 0.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/app/codexhost-distribution.json +1 -1
- package/app/console-server.mjs +479 -107
- package/app/console-web.js +1106 -145
- package/app/desktop-controller.mjs +356 -63
- package/app/host-runtime.mjs +4345 -1470
- package/app/plugins/antigravity/plugin.mjs +1002 -99
- package/app/plugins/claude-code/plugin.mjs +336 -61
- package/app/plugins/codebuddy/plugin.mjs +389 -84
- package/app/plugins/codex-usage/plugin.mjs +468 -65
- package/app/plugins/copilot/plugin.mjs +336 -63
- package/app/plugins/cursor-cli/plugin.mjs +336 -61
- package/app/plugins/deepseek-harness/plugin.mjs +336 -61
- package/app/plugins/devin/plugin.mjs +336 -61
- package/app/plugins/grok/plugin.mjs +389 -83
- package/app/plugins/hermes/plugin.mjs +335 -60
- package/app/plugins/kimi-code/plugin.mjs +336 -61
- package/app/plugins/kiro-cli/plugin.mjs +336 -61
- package/app/plugins/omp/plugin.mjs +336 -61
- package/app/plugins/opencode/plugin.mjs +336 -61
- package/app/plugins/pi/plugin.mjs +336 -61
- package/app/plugins/qoder/plugin.mjs +337 -62
- package/app/plugins/qoder-cn/plugin.mjs +337 -62
- package/app/plugins/qwen-code/plugin.mjs +335 -60
- package/app/plugins/workbuddy/plugin.mjs +408 -95
- package/app/plugins/workbuddy-cn/plugin.mjs +408 -95
- package/app/plugins/zcode/plugin.mjs +337 -61
- package/app/renderer-extension.js +1516 -346
- package/app/web/assets/{abnfDiagram-XWFEHMT6-Cg-E7mc4.js → abnfDiagram-XWFEHMT6-CGkBtBVj.js} +1 -1
- package/app/web/assets/{architectureDiagram-CSQXQB3N-B__CwXjW.js → architectureDiagram-CSQXQB3N-Byv-cZeH.js} +1 -1
- package/app/web/assets/{blockDiagram-BEDRHYPZ-Bk2gCIVM.js → blockDiagram-BEDRHYPZ-DjLzUtwg.js} +1 -1
- package/app/web/assets/{c4Diagram-M2UUVUY5-DU_TpjJ3.js → c4Diagram-M2UUVUY5-CJlsb6QO.js} +1 -1
- package/app/web/assets/{chunk-2Q5K7J3B-DnJEi6e4.js → chunk-2Q5K7J3B-CWm537bw.js} +1 -1
- package/app/web/assets/{chunk-3GCGMST5-Dia9jGkf.js → chunk-3GCGMST5-NpcInIx4.js} +1 -1
- package/app/web/assets/{chunk-5VM5RSS4-2PGDiDvK.js → chunk-5VM5RSS4-CeyyP0dm.js} +1 -1
- package/app/web/assets/{chunk-7U7NFRK5-BLPm3d5H.js → chunk-7U7NFRK5-Bto5OgbF.js} +1 -1
- package/app/web/assets/{chunk-CNRTWJTD-GH_nAEXs.js → chunk-CNRTWJTD-CuRMFCjT.js} +1 -1
- package/app/web/assets/{chunk-D5HYT7QG-DnIm-Ely.js → chunk-D5HYT7QG-DtQM1-2k.js} +1 -1
- package/app/web/assets/{chunk-EBZ3SEQC-C6N5qLCR.js → chunk-EBZ3SEQC-DbUb3ZJ4.js} +2 -2
- package/app/web/assets/{chunk-JWPE2WC7-D_kMgdmr.js → chunk-JWPE2WC7-Dxh3d9Ag.js} +1 -1
- package/app/web/assets/{chunk-KTR4FSNJ-BRb9femQ.js → chunk-KTR4FSNJ-BfwavXUO.js} +1 -1
- package/app/web/assets/{chunk-XXDRQBXY-BFaK95zq.js → chunk-XXDRQBXY-CxR1flID.js} +1 -1
- package/app/web/assets/{classDiagram-v2-KXABOMEV--_hR_XrU.js → classDiagram-v2-KXABOMEV-2WV2q_X2.js} +1 -1
- package/app/web/assets/{cose-bilkent-JH36ORCC-C7ghEB3_.js → cose-bilkent-JH36ORCC-C-ENrCL_.js} +1 -1
- package/app/web/assets/{cynefin-EF2NZ3EQ-Ce1lURwZ.js → cynefin-EF2NZ3EQ-Bg5LeTZO.js} +1 -1
- package/app/web/assets/{cynefinDiagram-NJNITYFG-Cgr5aSTS.js → cynefinDiagram-NJNITYFG-CRAdbGGt.js} +1 -1
- package/app/web/assets/{dagre-KIHZ2IZ3-BBFKmRP1.js → dagre-KIHZ2IZ3-dNHEvUqL.js} +1 -1
- package/app/web/assets/{diagram-7YQZDPLS-CJQih32K.js → diagram-7YQZDPLS-7F4O37o5.js} +1 -1
- package/app/web/assets/{diagram-QBROCOUO-Cl3S7IUT.js → diagram-QBROCOUO-B-5KpeI2.js} +1 -1
- package/app/web/assets/{diagram-RJJCUUZO-B6C8N2cV.js → diagram-RJJCUUZO-DqDsyDaL.js} +1 -1
- package/app/web/assets/{diagram-WERXNKYE-NkciBSQl.js → diagram-WERXNKYE-f1oaPKos.js} +1 -1
- package/app/web/assets/{diagram-YHHI257C-DlEvljeY.js → diagram-YHHI257C-DVMtl9Bt.js} +1 -1
- package/app/web/assets/{diagram-YR4HJLHV-e4_Gzbt6.js → diagram-YR4HJLHV-BWFCNFFF.js} +1 -1
- package/app/web/assets/{ebnfDiagram-N527522P-WvQEFmPi.js → ebnfDiagram-N527522P-B4N7d-Bi.js} +1 -1
- package/app/web/assets/{elk-O5DQBFGD-CkyJsjzf.js → elk-O5DQBFGD-DRdfF_UQ.js} +1 -1
- package/app/web/assets/{erDiagram-K3K3BIDK-B93gK3X0.js → erDiagram-K3K3BIDK-BW4-_5sZ.js} +1 -1
- package/app/web/assets/{flowDiagram-Z6JWZHQI-NFaGX6B4.js → flowDiagram-Z6JWZHQI-DIQa5yEv.js} +1 -1
- package/app/web/assets/{ganttDiagram-3PRQTZWP-Czh68CQm.js → ganttDiagram-3PRQTZWP-JBK9PM7A.js} +1 -1
- package/app/web/assets/{gitGraphDiagram-VXDFKS5L-t95UHKja.js → gitGraphDiagram-VXDFKS5L-TPI9Su0g.js} +1 -1
- package/app/web/assets/{grid-E2QIVN74-C87DucDN.js → grid-E2QIVN74-DmHbunuP.js} +1 -1
- package/app/web/assets/index-BKDmniRf.js +209 -0
- package/app/web/assets/index-BPMnQdGr.css +1 -0
- package/app/web/assets/{infoDiagram-EZ3ZOAHP-CxFlfQbY.js → infoDiagram-EZ3ZOAHP-BeFwO9PI.js} +1 -1
- package/app/web/assets/{ishikawaDiagram-S3EKX5GW-D4IwQJde.js → ishikawaDiagram-S3EKX5GW-BTbrKF_p.js} +1 -1
- package/app/web/assets/{journeyDiagram-POQNLL5X-C0Bf5W4T.js → journeyDiagram-POQNLL5X-DR0yWxJi.js} +1 -1
- package/app/web/assets/{kanban-definition-BH5XI6FM-Cda7r2yr.js → kanban-definition-BH5XI6FM-DMHrC9oV.js} +1 -1
- package/app/web/assets/{mermaid.core-f4LJm6AC.js → mermaid.core-Brmc1kJw.js} +4 -4
- package/app/web/assets/{mindmap-definition-WVAN44T4-DKapinG7.js → mindmap-definition-WVAN44T4-NT_XVwlI.js} +1 -1
- package/app/web/assets/{pegDiagram-D4NLKWP3-D7iEZGN2.js → pegDiagram-D4NLKWP3-K67_THcc.js} +1 -1
- package/app/web/assets/{pieDiagram-36ENHN4W-CopXZ5qt.js → pieDiagram-36ENHN4W-GlTgKnTi.js} +1 -1
- package/app/web/assets/{quadrantDiagram-ZQUDMS73-mmkKPDGK.js → quadrantDiagram-ZQUDMS73-yMEZ6-Nr.js} +1 -1
- package/app/web/assets/{railroadDiagram-JIZHGYPL-BAGwIIkV.js → railroadDiagram-JIZHGYPL-MXCqwbuq.js} +1 -1
- package/app/web/assets/{render-VIF2ZAQL-dXxGa09y.js → render-VIF2ZAQL-BRUlhHPG.js} +2 -2
- package/app/web/assets/{requirementDiagram-AXW2TVFA-C35tmLFs.js → requirementDiagram-AXW2TVFA-Dqx4p0Bz.js} +1 -1
- package/app/web/assets/{sankeyDiagram-FBCJTAIF-BbSo5yeK.js → sankeyDiagram-FBCJTAIF-COp3IWvs.js} +1 -1
- package/app/web/assets/{sequenceDiagram-3LA2ROMG-Cgm2unNy.js → sequenceDiagram-3LA2ROMG-j1xwrmp8.js} +1 -1
- package/app/web/assets/{sizeCapture-2Q2CQKSF-DCXFjl2x.js → sizeCapture-2Q2CQKSF-ZEXdxLeY.js} +1 -1
- package/app/web/assets/{stateDiagram-v2-ATKHQDJO-B349iAao.js → stateDiagram-v2-ATKHQDJO-2pt2L-Zd.js} +1 -1
- package/app/web/assets/{swimlanes-YQL5WMAO-6OvL1sEz.js → swimlanes-YQL5WMAO-BHpgfPPd.js} +1 -1
- package/app/web/assets/swimlanesDiagram-UCCPES4V-BrYKheZO.js +8 -0
- package/app/web/assets/{timeline-definition-7Z437IG3-Bh1E3mhW.js → timeline-definition-7Z437IG3-Cw4F_3FM.js} +1 -1
- package/app/web/assets/{usecaseDiagram-RDK6N6HP-Dr5A05lL.js → usecaseDiagram-RDK6N6HP-DefiMBIg.js} +1 -1
- package/app/web/assets/{vennDiagram-SHRQU5PJ-CQPPBa27.js → vennDiagram-SHRQU5PJ-D30EMFrI.js} +1 -1
- package/app/web/assets/{wardleyDiagram-F3OXNVQS-BHin00q8.js → wardleyDiagram-F3OXNVQS-4ok25PKp.js} +1 -1
- package/app/web/assets/{xychartDiagram-GDYJKCDI-D4BAWlQZ.js → xychartDiagram-GDYJKCDI-BB0uAQX5.js} +1 -1
- package/app/web/codexhost-settings.js +157 -87
- package/app/web/index.html +2 -2
- package/app/web/plugins/deepseek-ai__dsh-api-gateway/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +63 -63
- package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +70 -70
- package/app/web/plugins/deepseek-ai__dsh-client-file-upload/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +75 -75
- package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +90 -78
- package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +98 -98
- package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +65 -65
- package/app/web/plugins/deepseek-ai__dsh-client-ui-session/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-settings-general/client.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-documentpreview/client.pdf.js +1 -1
- package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-right/client.js +62 -62
- package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +80 -80
- package/app/web/plugins/deepseek-ai__dsh-client-ui-workspace/client.js +70 -70
- package/app/web/plugins.json +1 -0
- package/app/web-modules/server.mjs +1862 -1096
- package/bin/codexhost.exe +0 -0
- package/libexec/codexhost-node-repl.exe +0 -0
- package/libexec/codexhost-screenshot.exe +0 -0
- package/libexec/codexhost-shell.exe +0 -0
- package/libexec/codexhost-shim.exe +0 -0
- package/libexec/codexhost-updater.exe +0 -0
- package/package.json +1 -1
- package/app/web/assets/index-CGI50Nfg.css +0 -1
- package/app/web/assets/index-Dr6wHi0A.js +0 -208
- package/app/web/assets/swimlanesDiagram-UCCPES4V-CIKaQUvP.js +0 -8
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,factory:e=>{var t={exports:{}},n=t.exports;Object.defineProperty(n,Symbol.toStringTag,{value:`Module`});let r=e("@deepseek-ai/cordis"),i=e("@deepseek-ai/dsh-api-gateway/client"),a=e("@deepseek-ai/dsh-client-store");var o=class extends Error{code;details;isDSHRemoteError=!0;constructor(e,t,n,r){super(t,r),this.code=e,this.details=n,this.name=`RemoteError`}};let s=Symbol.for(`dsh.typert.owned-value`);function c(e,t){let n=!0;return{[s]:!0,value:e,[Symbol.dispose](){n&&(n=!1,t())}}}function l(e){return e}function u(e){return e.event.seq}function d(e){return e.event.seq}function f(e){return e}function p(e){if(!Number.isSafeInteger(e)||e<0||Object.is(e,-0))throw TypeError(`SessionSeq must be a non-negative safe integer, got ${String(e)}`);return f(e)}function 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=>Je(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`]),Ge=/* @__PURE__*/ new Set([`string`,`number`,`bigint`,`boolean`,`symbol`,`undefined`]);function Ke(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function qe(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 Je(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Ye(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}let Xe={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ze={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function Qe(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,$e(e,t)),qe(e,h(n,{shape:i,checks:[]}))}function $e(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 et(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($e(e,t)),a={};return Fe(a,e,Reflect.ownKeys(Me(e)).filter(e=>!i.has(e))),qe(e,h(n,{shape:a,checks:[]}))}function tt(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 qe(e,h(e._zod.def,{shape:nt(e,t)}))}function nt(e,t){let n={};return Fe(n,e,Reflect.ownKeys(Me(e))),Ie(n,t),n}function rt(e,t){if(!He(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return qe(e,h(e._zod.def,{shape:nt(e,t)}))}function it(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))),qe(e,h(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function at(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($e(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}))),qe(t,h(t._zod.def,{shape:o,checks:[]}))}function ot(e,t,n){let r=n?new Set($e(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})),qe(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 st(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 ct(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function lt(e){return typeof e==`string`?e:e?.message}function ut(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 dt(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function ft(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:lt(e.inst?._zod.def?.error?.(e))??lt(a?.(e))??lt(t?.error?.(e))??lt(n.customError?.(e))??lt(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 pt=/[\uD800-\uDBFF]/;function mt(e){let t=e.length;if(!pt.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 ht(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function gt(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 _t(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function vt(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):St(e,n,r.value)}}function yt(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function bt(e,t,n){return yt(e,t,n,!1)}function xt(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return yt(this,n,r(this))},set(e){yt(this,n,e)}})}return t}function St(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:yt(this,t,n.bind(this))},set(e){yt(this,t,e)}})}function Ct(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let wt,Tt=!1,Et={configurable:!0,get(){Tt=!0}};function v(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&wt!==e._zod?wt=void 0:(wt=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Et);let e=Tt;Tt=!1;try{let r=n(this);return Tt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Tt||=e,r}catch(n){throw delete this[t],Tt||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Dt(e,t,n,r){let i=Ct(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 Ot(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var kt;let At=/*@__PURE__*/ Object.freeze({status:`aborted`}),jt={value:void 0,enumerable:!1},Mt=`captureStackTrace`in Error?Error:null;function Nt(e){let t=Mt;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Mt=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){jt.value=new a(r);try{Object.defineProperty(n,"_zod",jt)}finally{jt.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),vt(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?Nt(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 Pt=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Ft=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(kt=globalThis).__zod_globalConfig??(kt.__zod_globalConfig={});let b=globalThis.__zod_globalConfig;function It(e){return e&&Object.assign(b,e),b}function Lt(){let e=this._zod;return e.message??=JSON.stringify(e.def,Se,2),e.message}function Rt(e){this._zod.message=e}let zt={get:Lt,set:Rt,enumerable:!0,configurable:!0},Bt={value:void 0,enumerable:!1},Vt=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Ht=(e,t)=>{e.name=`$ZodError`,Bt.value=t,Object.defineProperty(e,"issues",Bt),Bt.value=void 0,Object.defineProperty(e,"message",zt);let n=Object.getPrototypeOf(e);Vt.has(n)||(Vt.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})}}))},Ut=y(`$ZodError`,Ht);y(`$ZodError`,Ht,void 0,{Parent:Error});function Wt(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 Gt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Wt(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Kt(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 qt(e,t){return{callee:t?.callee??e,Err:t?.Err}}let Jt=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 Pt;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>ft(e,o,It())));throw ze(n,a?.callee??t),n}return s.value};return t},Yt=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=>ft(e,o,It())));throw ze(n,a?.callee??t),n}return s.value};return t},Xt=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 Pt;return a.issues.length?Zt(e,a.issues,i):{success:!0,data:a.value}};function Zt(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>ft(e,n,It()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}let Qt=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?Zt(e,a.issues,i):{success:!0,data:a.value}},$t=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),en=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),tn=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==$t)return!0;if(r.definite===!0&&n===void 0)return!1}return nn(e,t,n)});function nn(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[en]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new Pt;return a.issues.length===0}let rn=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},an=e=>{let t=Jt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,qt(n,a))};return n},on=e=>{let t=Jt(e),n=(e,r,i,a)=>t(e,r,i,qt(n,a));return n},sn=e=>{let t=Yt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,qt(n,a))};return n},cn=e=>{let t=Yt(e),n=async(e,r,i,a)=>await t(e,r,i,qt(n,a));return n},ln=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Xt(e)(t,n,i)},un=e=>(t,n,r)=>Xt(e)(t,n,r),dn=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Qt(e)(t,n,i)},fn=e=>async(t,n,r)=>Qt(e)(t,n,r),pn=/^[cC][0-9a-z]{6,}$/,mn=/^[0-9a-z]+$/,hn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,gn=/^[0-9a-vA-V]{20}$/,_n=/^[A-Za-z0-9]{27}$/,vn=/^[a-zA-Z0-9_-]{21}$/;function yn(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}let bn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xn=/^([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})$/,Sn=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)$/,Cn=/^(?:[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 wn(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}let 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])$/,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}|:))$/,Dn=/^((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])$/,On=/^(([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])$/,kn=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,An=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,jn=/^https?$/,Mn=/^\+[1-9]\d{6,14}$/,Nn=`(?:(?:\\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 Pn(e){return RegExp(`^${e}$`)}let Fn=/*@__PURE__*/ Pn(Nn);function In(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 Ln(e){return RegExp(`^${In(e)}$`)}function Rn(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${In({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${In({precision:e.precision})}`:n;return RegExp(`^${Nn}T(?:${r})$`)}let zn=/^[\s\S]{0,}$/,Bn=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Vn=/^-?\d+$/,Hn=/^-?\d+(?:\.\d+)?$/,Un=/^(?:true|false)$/i,Wn=/^null$/i,Gn=/^[^A-Z]*$/,Kn=/^[^a-z]*$/,x=/*@__PURE__*/ y(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),qn=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},Jn={number:`number`,bigint:`bigint`,object:`date`},Yn=/*@__PURE__*/ y(`$ZodCheckLessThan`,(e,t)=>{x.init(e,t);let n=Jn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Jn[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})}}),Xn=/*@__PURE__*/ y(`$ZodCheckGreaterThan`,(e,t)=>{x.init(e,t);let n=Jn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Jn[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})}}),Zn=/*@__PURE__*/ y(`$ZodCheckMultipleOf`,(e,t)=>{x.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})}}),Qn=/*@__PURE__*/ y(`$ZodCheckNumberFormat`,(e,t)=>{x.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Xe[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})}}),$n=/*@__PURE__*/ y(`$ZodCheckMaxLength`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?mt(r):i)<=t.maximum)return;let a=ht(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),er=/*@__PURE__*/ y(`$ZodCheckMinLength`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?mt(r):i)>=t.minimum)return;let a=ht(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),tr=/*@__PURE__*/ y(`$ZodCheckLengthEquals`,(e,t)=>{var n;x.init(e,t),(n=e._zod.def).when??(n.when=qn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?mt(r):i;if(a===t.length)return;let o=ht(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})}}),nr=/*@__PURE__*/ y(`$ZodCheckStringFormat`,(e,t)=>{var n,r;x.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=()=>{})}),rr=/*@__PURE__*/ y(`$ZodCheckRegex`,(e,t)=>{nr.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})}}),ir=/*@__PURE__*/ y(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Gn,nr.init(e,t)}),ar=/*@__PURE__*/ y(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Kn,nr.init(e,t)}),or=/*@__PURE__*/ y(`$ZodCheckIncludes`,(e,t)=>{x.init(e,t);let n=Ke(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})}}),sr=/*@__PURE__*/ y(`$ZodCheckStartsWith`,(e,t)=>{x.init(e,t);let n=RegExp(`^${Ke(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})}}),cr=/*@__PURE__*/ y(`$ZodCheckEndsWith`,(e,t)=>{x.init(e,t);let n=RegExp(`.*${Ke(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})}}),lr=/*@__PURE__*/ y(`$ZodCheckOverwrite`,(e,t)=>{x.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var ur=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(`
|
|
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,i=!1;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`,{});i=e.length===0,e=i?r.records:[...r.records,...e],t=r.hasMore}let s=a.epoch!==void 0&&a.epoch!==this.epoch;this.epoch=a.epoch,n=a.assistantStream.revision,yield{type:`opened`,...s?{reset:!0}:{},...i&&!s?{unchanged:!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=>Ke(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}function Oe(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ke(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Ae(e){return ke(e._zod.def)??e._zod.def.shape}function je(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Oe(this,t,e),e},enumerable:!0,configurable:!0})}function Me(e,t,n){t in e?Oe(e,t,n):e[t]=n}function Ne(e,t,n,r){let i=Ae(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?je(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Me(e,a,r?r(n.value,a):n.value))}}function Pe(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?je(e,n,()=>t[n]):Me(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 Fe(e){return JSON.stringify(e)}function Ie(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}let Le=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Re(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}let ze=/* @__PURE__*/ we(()=>{if(y.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Be(e){if(Re(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Re(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Ve(e){return Be(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}let He=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]),Ue=/* @__PURE__*/ new Set([`string`,`number`,`bigint`,`boolean`,`symbol`,`undefined`]);function We(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ge(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 Ke(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function qe(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}let Je={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ye={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function Xe(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 Ne(i,e,Ze(e,t)),Ge(e,h(n,{shape:i,checks:[]}))}function Ze(e,t){let n=Ae(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 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`);let i=new Set(Ze(e,t)),a={};return Ne(a,e,Reflect.ownKeys(Ae(e)).filter(e=>!i.has(e))),Ge(e,h(n,{shape:a,checks:[]}))}function $e(e,t){if(!Be(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Ae(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 Ge(e,h(e._zod.def,{shape:et(e,t)}))}function et(e,t){let n={};return Ne(n,e,Reflect.ownKeys(Ae(e))),Pe(n,t),n}function tt(e,t){if(!Be(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ge(e,h(e._zod.def,{shape:et(e,t)}))}function nt(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 Ne(n,e,Reflect.ownKeys(Ae(e))),Ne(n,t,Reflect.ownKeys(Ae(t))),Ge(e,h(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function rt(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(Ze(t,n)):void 0,o={};return Ne(o,t,Reflect.ownKeys(Ae(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Ge(t,h(t._zod.def,{shape:o,checks:[]}))}function it(e,t,n){let r=n?new Set(Ze(t,n)):void 0,i={};return Ne(i,t,Reflect.ownKeys(Ae(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Ge(t,h(t._zod.def,{shape:i}))}function at(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 _(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 v(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 y=globalThis.__zod_globalConfig;function Ft(e){return e&&Object.assign(y,e),y}function It(){let e=this._zod;return e.message??=JSON.stringify(e.def,Se,2),e.message}function Lt(e){this._zod.message=e}let Rt={get:It,set:Lt,enumerable:!0,configurable:!0},zt={value:void 0,enumerable:!1},Bt=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Vt=(e,t)=>{e.name=`$ZodError`,zt.value=t,Object.defineProperty(e,"issues",zt),zt.value=void 0,Object.defineProperty(e,"message",Rt);let n=Object.getPrototypeOf(e);Bt.has(n)||(Bt.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})}}))},Ht=v(`$ZodError`,Vt);v(`$ZodError`,Vt,void 0,{Parent:Error});function Ut(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 Wt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Ut(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Gt(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 Kt(e,t){return{callee:t?.callee??e,Err:t?.Err}}let qt=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,Ft())));throw Le(n,a?.callee??t),n}return s.value};return t},Jt=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,Ft())));throw Le(n,a?.callee??t),n}return s.value};return t},Yt=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?Xt(e,a.issues,i):{success:!0,data:a.value}};function Xt(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>dt(e,n,Ft()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}let Zt=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?Xt(e,a.issues,i):{success:!0,data:a.value}},Qt=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),$t=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),en=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Qt)return!0;if(r.definite===!0&&n===void 0)return!1}return tn(e,t,n)});function tn(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[$t]=!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 nn=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},rn=e=>{let t=qt(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Kt(n,a))};return n},an=e=>{let t=qt(e),n=(e,r,i,a)=>t(e,r,i,Kt(n,a));return n},on=e=>{let t=Jt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Kt(n,a))};return n},sn=e=>{let t=Jt(e),n=async(e,r,i,a)=>await t(e,r,i,Kt(n,a));return n},cn=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Yt(e)(t,n,i)},ln=e=>(t,n,r)=>Yt(e)(t,n,r),un=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Zt(e)(t,n,i)},dn=e=>async(t,n,r)=>Zt(e)(t,n,r),fn=/^[cC][0-9a-z]{6,}$/,pn=/^[0-9a-z]+$/,mn=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,hn=/^[0-9a-vA-V]{20}$/,gn=/^[A-Za-z0-9]{27}$/,_n=/^[a-zA-Z0-9_-]{21}$/;function vn(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}let yn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,bn=/^([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})$/,xn=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)$/,Sn=/^(?:[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 Cn(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}let wn=/^(?:(?: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])$/,Tn=/^(([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}|:))$/,En=/^((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])$/,Dn=/^(([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])$/,On=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kn=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,An=/^https?$/,jn=/^\+[1-9]\d{6,14}$/,Mn=`(?:(?:\\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 Nn(e){return RegExp(`^${e}$`)}let Pn=/*@__PURE__*/ Nn(Mn);function Fn(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 In(e){return RegExp(`^${Fn(e)}$`)}function Ln(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Fn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Fn({precision:e.precision})}`:n;return RegExp(`^${Mn}T(?:${r})$`)}let Rn=/^[\s\S]{0,}$/,zn=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Bn=/^-?\d+$/,Vn=/^-?\d+(?:\.\d+)?$/,Hn=/^(?:true|false)$/i,Un=/^null$/i,Wn=/^[^A-Z]*$/,Gn=/^[^a-z]*$/,b=/*@__PURE__*/ v(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Kn=e=>{let t=e.value;return!Te(t)&&t.length!==void 0},qn={number:`number`,bigint:`bigint`,object:`date`},Jn=/*@__PURE__*/ v(`$ZodCheckLessThan`,(e,t)=>{b.init(e,t);let n=qn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:qn[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})}}),Yn=/*@__PURE__*/ v(`$ZodCheckGreaterThan`,(e,t)=>{b.init(e,t);let n=qn[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:qn[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})}}),Xn=/*@__PURE__*/ v(`$ZodCheckMultipleOf`,(e,t)=>{b.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})}}),Zn=/*@__PURE__*/ v(`$ZodCheckNumberFormat`,(e,t)=>{b.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Je[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})}}),Qn=/*@__PURE__*/ v(`$ZodCheckMaxLength`,(e,t)=>{var n;b.init(e,t),(n=e._zod.def).when??(n.when=Kn),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})}}),$n=/*@__PURE__*/ v(`$ZodCheckMinLength`,(e,t)=>{var n;b.init(e,t),(n=e._zod.def).when??(n.when=Kn),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})}}),er=/*@__PURE__*/ v(`$ZodCheckLengthEquals`,(e,t)=>{var n;b.init(e,t),(n=e._zod.def).when??(n.when=Kn),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})}}),tr=/*@__PURE__*/ v(`$ZodCheckStringFormat`,(e,t)=>{var n,r;b.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=()=>{})}),nr=/*@__PURE__*/ v(`$ZodCheckRegex`,(e,t)=>{tr.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})}}),rr=/*@__PURE__*/ v(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Wn,tr.init(e,t)}),ir=/*@__PURE__*/ v(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Gn,tr.init(e,t)}),ar=/*@__PURE__*/ v(`$ZodCheckIncludes`,(e,t)=>{b.init(e,t);let n=We(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})}}),or=/*@__PURE__*/ v(`$ZodCheckStartsWith`,(e,t)=>{b.init(e,t);let n=RegExp(`^${We(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})}}),sr=/*@__PURE__*/ v(`$ZodCheckEndsWith`,(e,t)=>{b.init(e,t);let n=RegExp(`.*${We(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})}}),cr=/*@__PURE__*/ v(`$ZodCheckOverwrite`,(e,t)=>{b.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var lr=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
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 dr={major:4,minor:6,patch:7},S=/*@__PURE__*/ y(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=dr;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(st(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 Pt;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(dt(t.issues,n,e),i||=_(t,n))});else{if(t.issues.length===n)continue;dt(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 Pt;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 Pt;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return bt(this,`~standard`,mr(this))},set"~standard"(e){yt(this,`~standard`,e)}}),fr=(e,t)=>e.issues.length?{issues:e.issues.map(e=>ft(e,t,It()))}:{value:e.value};async function pr(e,t){let n={async:!0};return fr(await e._zod.run({value:t,issues:[]},n),n)}function mr(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return fr(r,n)}catch{}return pr(e,t)},vendor:`zod`,version:1}}let hr=/*@__PURE__*/ y(`$ZodString`,(e,t)=>{S.init(e,t),e._zod.pattern=t.pattern??zn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),C=/*@__PURE__*/ y(`$ZodStringFormat`,(e,t)=>{nr.init(e,t),hr.init(e,t)}),gr=/*@__PURE__*/ y(`$ZodGUID`,(e,t)=>{t.pattern??=xn,C.init(e,t)}),_r=/*@__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??=Sn(e)}else t.pattern??=Sn();C.init(e,t)}),vr=/*@__PURE__*/ y(`$ZodEmail`,(e,t)=>{t.pattern??=Cn,C.init(e,t)});function yr(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function br(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?yr(e)||2:xr(e,t)}function xr(e,t){if(!t.normalize&&t.protocol?.source===jn.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 Sr=/[\t\n\r]/g;function Cr(e){return e.replace(Sr,``)}function wr(e,t){return t.lastIndex=0,t.test(e.hostname)}function Tr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}let Er=/*@__PURE__*/ y(`$ZodURL`,(e,t)=>{C.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=br(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=Cr(r);return}t.hostname&&!wr(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&&!Tr(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:Cr(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Dr=/*@__PURE__*/ y(`$ZodEmoji`,(e,t)=>{t.pattern??=wn(),C.init(e,t)}),Or=/*@__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?vn:yn(t.length),C.init(e,t)}),kr=/*@__PURE__*/ y(`$ZodCUID`,(e,t)=>{t.pattern??=pn,C.init(e,t)}),Ar=/*@__PURE__*/ y(`$ZodCUID2`,(e,t)=>{t.pattern??=mn,C.init(e,t)}),jr=/*@__PURE__*/ y(`$ZodULID`,(e,t)=>{t.pattern??=hn,C.init(e,t)}),Mr=/*@__PURE__*/ y(`$ZodXID`,(e,t)=>{t.pattern??=gn,C.init(e,t)}),Nr=/*@__PURE__*/ y(`$ZodKSUID`,(e,t)=>{t.pattern??=_n,C.init(e,t)}),Pr=/*@__PURE__*/ y(`$ZodISODateTime`,(e,t)=>{t.pattern??=Rn(t),C.init(e,t)}),Fr=/*@__PURE__*/ y(`$ZodISODate`,(e,t)=>{t.pattern??=Fn,C.init(e,t)}),Ir=/*@__PURE__*/ y(`$ZodISOTime`,(e,t)=>{t.pattern??=Ln(t),C.init(e,t)}),Lr=/*@__PURE__*/ y(`$ZodISODuration`,(e,t)=>{t.pattern??=bn,C.init(e,t)}),Rr=/*@__PURE__*/ y(`$ZodIPv4`,(e,t)=>{t.pattern??=Tn,C.init(e,t)}),zr=/^[0-9a-fA-F:.]+$/;function Br(e){return zr.test(e)?yr(`http://[${e}]`):!1}let Vr=/*@__PURE__*/ y(`$ZodIPv6`,(e,t)=>{t.pattern??=En,C.init(e,t),e._zod.check=n=>{Br(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Hr=/*@__PURE__*/ y(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Dn,C.init(e,t)});function Ur(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:Br(n)}let Wr=/*@__PURE__*/ y(`$ZodCIDRv6`,(e,t)=>{t.pattern??=On,C.init(e,t),e._zod.check=n=>{Ur(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Gr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let Kr=/^[0-9a-zA-Z+/]*={0,2}$/,qr=/*@__PURE__*/ y(`$ZodBase64`,(e,t)=>{t.pattern??=Kr,C.init(e,t),e._zod.check=n=>{Gr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Jr=/^[A-Za-z0-9_-]*$/;function Yr(e){if(!Jr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Gr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}let Xr=/*@__PURE__*/ y(`$ZodBase64URL`,(e,t)=>{t.pattern??=Jr,C.init(e,t),e._zod.check=n=>{Yr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Zr=/*@__PURE__*/ y(`$ZodE164`,(e,t)=>{t.pattern??=Mn,C.init(e,t)});function Qr(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 $r=/*@__PURE__*/ y(`$ZodJWT`,(e,t)=>{C.init(e,t),e._zod.check=n=>{Qr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),ei=/*@__PURE__*/ y(`$ZodNumber`,(e,t)=>{S.init(e,t),e._zod.pattern=Hn,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}}),ti=/*@__PURE__*/ y(`$ZodNumberFormat`,(e,t)=>{Qn.init(e,t),ei.init(e,t)}),ni=/*@__PURE__*/ y(`$ZodBoolean`,(e,t)=>{S.init(e,t),e._zod.pattern=Un,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}}),ri=/*@__PURE__*/ y(`$ZodNull`,(e,t)=>{S.init(e,t),e._zod.pattern=Wn,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}}),ii=/*@__PURE__*/ y(`$ZodUnknown`,(e,t)=>{S.init(e,t),e._zod.parse=e=>e}),ai=/*@__PURE__*/ y(`$ZodNever`,(e,t)=>{S.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function oi(e,t){let n=ut(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 ut(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,dt(n.issues,t,e),n}}return i(n,a)}}let si=e=>Array.isArray(e)?e.length:-1;function ci(e,t,n){e.issues.length&&t.issues.push(...ct(n,e.issues)),t.value[n]=e.value}let li=/*@__PURE__*/ y(`$ZodArray`,(e,t)=>{S.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=>ci(t,r,e)));else if(ci(c,r,e),s&&c.issues.length!==0&&_(c))break}return o.length?Promise.all(o).then(()=>r):r},oi(e,si)});function ui(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(...ct(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 di=[];function fi(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:di,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=Ye(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function pi(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=>ui(e,n,i,t,d,f))):ui(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 mi=/*@__PURE__*/ y(`$ZodObject`,(e,t)=>{S.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(()=>fi(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=>ui(n,t,e,r,a,o))):ui(s,t,e,r,a,o)}return o?pi(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),hi=/*@__PURE__*/ y(`$ZodObjectJIT`,(e,t)=>{mi.init(e,t);let n=e._zod.parse,r=we(()=>fi(t)),i=b.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new ur([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
|
|
3
|
+
`)}\n};`)(...Object.values(this.closed))}};let ur={major:4,minor:6,patch:7},x=/*@__PURE__*/ v(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ur;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=at(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||=at(t,n))});else{if(t.issues.length===n)continue;ut(t.issues,n,e),i||=at(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(at(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`,pr(this))},set"~standard"(e){vt(this,`~standard`,e)}}),dr=(e,t)=>e.issues.length?{issues:e.issues.map(e=>dt(e,t,Ft()))}:{value:e.value};async function fr(e,t){let n={async:!0};return dr(await e._zod.run({value:t,issues:[]},n),n)}function pr(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return dr(r,n)}catch{}return fr(e,t)},vendor:`zod`,version:1}}let mr=/*@__PURE__*/ v(`$ZodString`,(e,t)=>{x.init(e,t),e._zod.pattern=t.pattern??Rn,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__*/ v(`$ZodStringFormat`,(e,t)=>{tr.init(e,t),mr.init(e,t)}),hr=/*@__PURE__*/ v(`$ZodGUID`,(e,t)=>{t.pattern??=bn,S.init(e,t)}),gr=/*@__PURE__*/ v(`$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??=xn(e)}else t.pattern??=xn();S.init(e,t)}),_r=/*@__PURE__*/ v(`$ZodEmail`,(e,t)=>{t.pattern??=Sn,S.init(e,t)});function vr(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function yr(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?vr(e)||2:br(e,t)}function br(e,t){if(!t.normalize&&t.protocol?.source===An.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 xr=/[\t\n\r]/g;function Sr(e){return e.replace(xr,``)}function Cr(e,t){return t.lastIndex=0,t.test(e.hostname)}function wr(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}let Tr=/*@__PURE__*/ v(`$ZodURL`,(e,t)=>{S.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=yr(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=Sr(r);return}t.hostname&&!Cr(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&&!wr(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:Sr(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Er=/*@__PURE__*/ v(`$ZodEmoji`,(e,t)=>{t.pattern??=Cn(),S.init(e,t)}),Dr=/*@__PURE__*/ v(`$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?_n:vn(t.length),S.init(e,t)}),Or=/*@__PURE__*/ v(`$ZodCUID`,(e,t)=>{t.pattern??=fn,S.init(e,t)}),kr=/*@__PURE__*/ v(`$ZodCUID2`,(e,t)=>{t.pattern??=pn,S.init(e,t)}),Ar=/*@__PURE__*/ v(`$ZodULID`,(e,t)=>{t.pattern??=mn,S.init(e,t)}),jr=/*@__PURE__*/ v(`$ZodXID`,(e,t)=>{t.pattern??=hn,S.init(e,t)}),Mr=/*@__PURE__*/ v(`$ZodKSUID`,(e,t)=>{t.pattern??=gn,S.init(e,t)}),Nr=/*@__PURE__*/ v(`$ZodISODateTime`,(e,t)=>{t.pattern??=Ln(t),S.init(e,t)}),Pr=/*@__PURE__*/ v(`$ZodISODate`,(e,t)=>{t.pattern??=Pn,S.init(e,t)}),Fr=/*@__PURE__*/ v(`$ZodISOTime`,(e,t)=>{t.pattern??=In(t),S.init(e,t)}),Ir=/*@__PURE__*/ v(`$ZodISODuration`,(e,t)=>{t.pattern??=yn,S.init(e,t)}),Lr=/*@__PURE__*/ v(`$ZodIPv4`,(e,t)=>{t.pattern??=wn,S.init(e,t)}),Rr=/^[0-9a-fA-F:.]+$/;function zr(e){return Rr.test(e)?vr(`http://[${e}]`):!1}let Br=/*@__PURE__*/ v(`$ZodIPv6`,(e,t)=>{t.pattern??=Tn,S.init(e,t),e._zod.check=n=>{zr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Vr=/*@__PURE__*/ v(`$ZodCIDRv4`,(e,t)=>{t.pattern??=En,S.init(e,t)});function Hr(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:zr(n)}let Ur=/*@__PURE__*/ v(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Dn,S.init(e,t),e._zod.check=n=>{Hr(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Wr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}let Gr=/^[0-9a-zA-Z+/]*={0,2}$/,Kr=/*@__PURE__*/ v(`$ZodBase64`,(e,t)=>{t.pattern??=Gr,S.init(e,t),e._zod.check=n=>{Wr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),qr=/^[A-Za-z0-9_-]*$/;function Jr(e){if(!qr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Wr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}let Yr=/*@__PURE__*/ v(`$ZodBase64URL`,(e,t)=>{t.pattern??=qr,S.init(e,t),e._zod.check=n=>{Jr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Xr=/*@__PURE__*/ v(`$ZodE164`,(e,t)=>{t.pattern??=jn,S.init(e,t)});function Zr(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 Qr=/*@__PURE__*/ v(`$ZodJWT`,(e,t)=>{S.init(e,t),e._zod.check=n=>{Zr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),$r=/*@__PURE__*/ v(`$ZodNumber`,(e,t)=>{x.init(e,t),e._zod.pattern=Vn,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}}),ei=/*@__PURE__*/ v(`$ZodNumberFormat`,(e,t)=>{Zn.init(e,t),$r.init(e,t)}),ti=/*@__PURE__*/ v(`$ZodBoolean`,(e,t)=>{x.init(e,t),e._zod.pattern=Hn,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}}),ni=/*@__PURE__*/ v(`$ZodNull`,(e,t)=>{x.init(e,t),e._zod.pattern=Un,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}}),ri=/*@__PURE__*/ v(`$ZodUnknown`,(e,t)=>{x.init(e,t),e._zod.parse=e=>e}),ii=/*@__PURE__*/ v(`$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 ai(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 oi=e=>Array.isArray(e)?e.length:-1;function si(e,t,n){e.issues.length&&t.issues.push(...st(n,e.issues)),t.value[n]=e.value}let ci=/*@__PURE__*/ v(`$ZodArray`,(e,t)=>{x.init(e,t);let n=y.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=>si(t,r,e)));else if(si(c,r,e),s&&c.issues.length!==0&&at(c))break}return o.length?Promise.all(o).then(()=>r):r},ai(e,oi)});function li(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 ui=[];function di(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:ui,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=qe(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function fi(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(at(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=>li(e,n,i,t,d,f))):li(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 pi=/*@__PURE__*/ v(`$ZodObject`,(e,t)=>{x.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(()=>di(t));_(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)||Oe(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=Re,o=t.catchall,s,c=y.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(at(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=>li(n,t,e,r,a,o))):li(s,t,e,r,a,o)}return o?fi(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),mi=/*@__PURE__*/ v(`$ZodObjectJIT`,(e,t)=>{pi.init(e,t);let n=e._zod.parse,r=we(()=>di(t)),i=y.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new lr([`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
4
|
let ${e}_ab = false;
|
|
5
5
|
for (let i = 0; i < ${e}.issues.length; i++) {
|
|
6
6
|
const iss = ${e}.issues[i];
|
|
@@ -11,7 +11,7 @@ window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,facto
|
|
|
11
11
|
if (${e}_ab && ctx && ctx.abortEarly) {
|
|
12
12
|
payload.value = newResult;
|
|
13
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)}]`:
|
|
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)}]`:Fe(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
15
|
const ${n}_present = ${i};
|
|
16
16
|
if (!${n}.issues.length || ${n}_present) {
|
|
17
17
|
if (${n}.issues.length) {${c(n,r)}
|
|
@@ -50,80 +50,80 @@ window.__ModuleLoader__.load({id:`@deepseek-ai/dsh-api-session-controller`,facto
|
|
|
50
50
|
newResult[${r}] = ${n}.value;
|
|
51
51
|
}
|
|
52
52
|
|
|
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?pi([],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 gi(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=>ft(e,r,It())))}),t)}let _i=/*@__PURE__*/ y(`$ZodUnion`,(e,t)=>{S.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=>gi(t,r,e,i)):gi(o,r,e,i)}});function vi(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 yi=/*@__PURE__*/ y(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,_i.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(()=>vi(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)}}),bi=/*@__PURE__*/ y(`$ZodIntersection`,(e,t)=>{S.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Si(e,t,n)):Si(e,i,a)}});function xi(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=xi(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=xi(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 Si(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=xi(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 Ci=/*@__PURE__*/ y(`$ZodTuple`,(e,t)=>{S.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=wi(n,`optin`),l=wi(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=>Ti(t,i,e))):Ti(r,i,e)}}return s.length?Promise.all(s).then(()=>Ei(u,i,n,o,l)):Ei(u,i,n,o,l)}});function wi(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 Ti(e,t,n){e.issues.length&&t.issues.push(...ct(n,e.issues)),t.value[n]=e.value}function Ei(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(...ct(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 Di=/*@__PURE__*/ y(`$ZodRecord`,(e,t)=>{S.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=>ft(e,i,It())),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(...ct(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...ct(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`&&Hn.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=>ft(e,i,It())),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(...ct(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...ct(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}}),Oi=/*@__PURE__*/ y(`$ZodEnum`,(e,t)=>{S.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=>Ke(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}}),ki=/*@__PURE__*/ y(`$ZodLiteral`,(e,t)=>{S.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`?Ke(e):e?Ke(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}}),Ai=/*@__PURE__*/ y(`$ZodTransform`,(e,t)=>{S.init(e,t),e._zod.optin=`optional`,b.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ft(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 Pt;return n.value=i,n}});function ji(e,t){return e.value=t.issues.length?void 0:t.value,e}let Mi=/*@__PURE__*/ y(`$ZodOptional`,(e,t)=>{S.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=>ji(e,t)):ji(e,r)}return t.innerType._zod.run(e,n)}}),Ni=/*@__PURE__*/ y(`$ZodExactOptional`,(e,t)=>{Mi.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)}),Pi=/*@__PURE__*/ y(`$ZodNullable`,(e,t)=>{S.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)}),Fi=/*@__PURE__*/ y(`$ZodDefault`,(e,t)=>{S.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=>Ii(e,t)):Ii(r,t)}});function Ii(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let Li=/*@__PURE__*/ y(`$ZodPrefault`,(e,t)=>{S.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))}),Ri=/*@__PURE__*/ y(`$ZodNonOptional`,(e,t)=>{S.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=>zi(t,e)):zi(i,e)}});function zi(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 Bi(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>ft(e,r,It()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}let Vi=/*@__PURE__*/ y(`$ZodCatch`,(e,t)=>{S.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=>Bi(e,r,t,n)):Bi(e,r,t,n)}}),Hi=/*@__PURE__*/ y(`$ZodPipe`,(e,t)=>{S.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=>Ui(e,t.in,n)):Ui(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ui(e,t.out,n)):Ui(r,t.out,n)}});function Ui(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 Wi=/*@__PURE__*/ y(`$ZodReadonly`,(e,t)=>{S.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(Gi):Gi(r)}});function Gi(e){return e.memo||(e.value=Object.freeze(e.value)),e}function Ki(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes(`int`),i,a;for(let e of t.checks??[]){let t=e._zod.def;t.pattern&&(n=t.pattern),r||=!!t.format?.includes(`int`);let o=t.minimum??t.length,s=t.maximum??t.length;o!==void 0&&(i===void 0||o>i)&&(i=o),s!==void 0&&(a===void 0||s<a)&&(a=s)}if(n)return n.source;if(i!==void 0&&a!==void 0&&i>a)return`(?!)`;if(i!==void 0||a!==void 0)return Bn({minimum:i,maximum:a}).source;let o=e._zod.pattern;return(r&&o===Hn?Vn:o)?.source}function qi(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let e=r._zod.pattern?.source,t=qi(r);return n&&e&&t&&t!==e?n.replace(Ee(e),()=>Ee(t)):n}if(t.options){let e=t.options.map(qi);if(e.every(Boolean))return`^(${e.map(e=>Ee(e)).join(`|`)})$`}return Ki(e)}let Ji=/*@__PURE__*/ y(`$ZodTemplateLiteral`,(e,t)=>{S.init(e,t);let n=[];for(let e of t.parts)if(typeof e==`object`&&e){let t=qi(e);if(!t)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);n.push(Ee(t))}else if(e===null||Ge.has(typeof e))n.push(Ke(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${n.join(``)}$`),e._zod.parse=(n,r)=>typeof n.value==`string`?(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:`invalid_format`,format:t.format??`template_literal`,pattern:e._zod.pattern.source}),n):(n.issues.push({input:n.value,inst:e,expected:`string`,code:`invalid_type`}),n)}),Yi=/*@__PURE__*/ y(`$ZodLazy`,(e,t)=>{S.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)}),Xi=/*@__PURE__*/ y(`$ZodCustom`,(e,t)=>{x.init(e,t),S.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Zi(t,n,r,e));Zi(i,n,r,e)}});function Zi(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(_t(e))}}var Qi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};let $i=`~memo`,ea=[];function ta(e){return typeof e==`object`&&!!e}function na(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let ra=/*@__PURE__*/ new WeakMap;function ia(e,t,n){let r=ra.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=ia(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?ia(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?ia(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),aa(e,i)}function aa(e,t){return t!==1&&ra.set(e,t===2),t}function oa(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let sa,ca=[],la={alloc(e,t,n){let r=sa;if(!r)return n;sa=void 0;let i={value:n,issues:null};return r.set(t.value,i),ca.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`&&da(n,e.value))throw new Qi;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=ia(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(!ta(l))return t(s,c);let u=c[$i];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[$i]=u);let d;i===c?d=a:(d=oa(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(...na(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;sa=d;let p=ca.length,m=t(s,c);sa=void 0;let ee=ca.length>p?ca.pop():void 0;return m instanceof Promise?m.then(e=>(ee&&(ee.issues=e.issues.length?na(e.issues):ea),e)):(ee&&(ee.issues=m.issues.length?na(m.issues):ea),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function ua(){return la}function da(e,t){let n=e[$i]?.backEdges;return n!==void 0&&ta(t)&&n.has(t)}let fa=()=>{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(gt(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Je(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 pa(){return{localeError:fa()}}var ma,ha=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 ga(){return new ha}(ma=globalThis).__zod_globalRegistry??(ma.__zod_globalRegistry=ga());let _a=globalThis.__zod_globalRegistry;function va(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
|
|
54
|
-
function
|
|
55
|
-
function
|
|
56
|
-
function
|
|
57
|
-
function
|
|
58
|
-
function
|
|
59
|
-
function
|
|
60
|
-
function
|
|
61
|
-
function
|
|
62
|
-
function
|
|
63
|
-
function
|
|
64
|
-
function
|
|
65
|
-
function
|
|
66
|
-
function
|
|
67
|
-
function
|
|
68
|
-
function
|
|
69
|
-
function
|
|
70
|
-
function
|
|
71
|
-
function
|
|
72
|
-
function
|
|
73
|
-
function
|
|
74
|
-
function
|
|
75
|
-
function
|
|
76
|
-
function
|
|
77
|
-
function
|
|
78
|
-
function
|
|
79
|
-
function
|
|
80
|
-
function
|
|
81
|
-
function
|
|
82
|
-
function
|
|
83
|
-
function
|
|
84
|
-
function
|
|
85
|
-
function
|
|
86
|
-
function
|
|
87
|
-
function
|
|
88
|
-
function
|
|
89
|
-
function
|
|
90
|
-
function
|
|
91
|
-
function
|
|
92
|
-
function
|
|
93
|
-
function
|
|
94
|
-
function
|
|
95
|
-
function
|
|
96
|
-
function
|
|
97
|
-
function
|
|
98
|
-
function
|
|
99
|
-
function
|
|
100
|
-
function
|
|
101
|
-
function
|
|
102
|
-
function
|
|
103
|
-
function
|
|
104
|
-
function
|
|
105
|
-
function
|
|
106
|
-
function
|
|
107
|
-
function
|
|
108
|
-
function
|
|
109
|
-
function
|
|
110
|
-
function
|
|
111
|
-
function
|
|
53
|
+
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Re,c=!y.jitless,l=c&&ze.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?fi([],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 hi(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=>!at(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,Ft())))}),t)}let gi=/*@__PURE__*/ v(`$ZodUnion`,(e,t)=>{x.init(e,t),_(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),_(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),_(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)))}),_(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=>hi(t,r,e,i)):hi(o,r,e,i)}});function _i(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 vi=/*@__PURE__*/ v(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,gi.init(e,t);let n=e._zod.parse;_(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)||Oe(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=ke(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=we(()=>_i(t));e._zod.parse=(i,a)=>{let o=i.value;if(!Re(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)}}),yi=/*@__PURE__*/ v(`$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])=>xi(e,t,n)):xi(e,i,a)}});function bi(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Be(e)&&Be(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=bi(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=bi(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 xi(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=bi(t.value,n.value);if(!c.valid){if(at(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}let Si=/*@__PURE__*/ v(`$ZodTuple`,(e,t)=>{x.init(e,t);let n=t.items,r=y.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=Ci(n,`optin`),l=Ci(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=at(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(at(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=>wi(t,i,e))):wi(r,i,e)}}return s.length?Promise.all(s).then(()=>Ti(u,i,n,o,l)):Ti(u,i,n,o,l)}});function Ci(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 wi(e,t,n){e.issues.length&&t.issues.push(...st(n,e.issues)),t.value[n]=e.value}function Ti(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 Ei=/*@__PURE__*/ v(`$ZodRecord`,(e,t)=>{x.init(e,t);let n=y.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Be(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,Ft())),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`&&Vn.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,Ft())),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}}),Di=/*@__PURE__*/ v(`$ZodEnum`,(e,t)=>{x.init(e,t);let n=be(t.entries),r=new Set(n);e._zod.values=r,_(e,`pattern`,e=>{let t=be(e.def.entries).filter(e=>He.has(typeof e));return RegExp(t.length?`^(${t.map(e=>We(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}}),Oi=/*@__PURE__*/ v(`$ZodLiteral`,(e,t)=>{x.init(e,t);let n=new Set(t.values);e._zod.values=n,_(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?We(e):e?We(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}}),ki=/*@__PURE__*/ v(`$ZodTransform`,(e,t)=>{x.init(e,t),e._zod.optin=`optional`,y.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 Ai(e,t){return e.value=t.issues.length?void 0:t.value,e}let ji=/*@__PURE__*/ v(`$ZodOptional`,(e,t)=>{x.init(e,t),_(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,_(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),_(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=>Ai(e,t)):Ai(e,r)}return t.innerType._zod.run(e,n)}}),Mi=/*@__PURE__*/ v(`$ZodExactOptional`,(e,t)=>{ji.init(e,t),_(e,`values`,e=>e.def.innerType._zod.values),_(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Ni=/*@__PURE__*/ v(`$ZodNullable`,(e,t)=>{x.init(e,t),_(e,`optin`,e=>e.def.innerType._zod.optin),_(e,`optout`,e=>e.def.innerType._zod.optout),_(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ee(t.source)}|null)$`):void 0}),_(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)}),Pi=/*@__PURE__*/ v(`$ZodDefault`,(e,t)=>{x.init(e,t),e._zod.optin=`defaulted`,_(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=>Fi(e,t)):Fi(r,t)}});function Fi(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}let Ii=/*@__PURE__*/ v(`$ZodPrefault`,(e,t)=>{x.init(e,t),e._zod.optin=`defaulted`,_(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))}),Li=/*@__PURE__*/ v(`$ZodNonOptional`,(e,t)=>{x.init(e,t),_(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=>Ri(t,e)):Ri(i,e)}});function Ri(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 zi(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,Ft()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}let Bi=/*@__PURE__*/ v(`$ZodCatch`,(e,t)=>{x.init(e,t),_(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),_(e,`optout`,e=>e.def.innerType._zod.optout),_(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=>zi(e,r,t,n)):zi(e,r,t,n)}}),Vi=/*@__PURE__*/ v(`$ZodPipe`,(e,t)=>{x.init(e,t),_(e,`values`,e=>e.def.in._zod.values),_(e,`optin`,e=>e.def.in._zod.optin),_(e,`optout`,e=>e.def.out._zod.optout),_(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=>Hi(e,t.in,n)):Hi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Hi(e,t.out,n)):Hi(r,t.out,n)}});function Hi(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 Ui=/*@__PURE__*/ v(`$ZodPreprocess`,(e,t)=>{Vi.init(e,t)}),Wi=/*@__PURE__*/ v(`$ZodReadonly`,(e,t)=>{x.init(e,t),_(e,`propValues`,e=>e.def.innerType._zod.propValues),_(e,`values`,e=>e.def.innerType._zod.values),_(e,`optin`,e=>e.def.innerType?._zod?.optin),_(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(Gi):Gi(r)}});function Gi(e){return e.memo||(e.value=Object.freeze(e.value)),e}function Ki(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes(`int`),i,a;for(let e of t.checks??[]){let t=e._zod.def;t.pattern&&(n=t.pattern),r||=!!t.format?.includes(`int`);let o=t.minimum??t.length,s=t.maximum??t.length;o!==void 0&&(i===void 0||o>i)&&(i=o),s!==void 0&&(a===void 0||s<a)&&(a=s)}if(n)return n.source;if(i!==void 0&&a!==void 0&&i>a)return`(?!)`;if(i!==void 0||a!==void 0)return zn({minimum:i,maximum:a}).source;let o=e._zod.pattern;return(r&&o===Vn?Bn:o)?.source}function qi(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let e=r._zod.pattern?.source,t=qi(r);return n&&e&&t&&t!==e?n.replace(Ee(e),()=>Ee(t)):n}if(t.options){let e=t.options.map(qi);if(e.every(Boolean))return`^(${e.map(e=>Ee(e)).join(`|`)})$`}return Ki(e)}let Ji=/*@__PURE__*/ v(`$ZodTemplateLiteral`,(e,t)=>{x.init(e,t);let n=[];for(let e of t.parts)if(typeof e==`object`&&e){let t=qi(e);if(!t)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);n.push(Ee(t))}else if(e===null||Ue.has(typeof e))n.push(We(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${n.join(``)}$`),e._zod.parse=(n,r)=>typeof n.value==`string`?(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:`invalid_format`,format:t.format??`template_literal`,pattern:e._zod.pattern.source}),n):(n.issues.push({input:n.value,inst:e,expected:`string`,code:`invalid_type`}),n)}),Yi=/*@__PURE__*/ v(`$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=>Xi(t,n,r,e));Xi(i,n,r,e)}});function Xi(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 Zi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};let Qi=`~memo`,$i=[];function ea(e){return typeof e==`object`&&!!e}function ta(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}let na=/*@__PURE__*/ new WeakMap;function ra(e,t,n){let r=na.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=ra(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?ra(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=ke(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?ra(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),ia(e,i)}function ia(e,t){return t!==1&&na.set(e,t===2),t}function aa(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let oa,sa=[],ca={alloc(e,t,n){let r=oa;if(!r)return n;oa=void 0;let i={value:n,issues:null};return r.set(t.value,i),sa.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`&&ua(n,e.value))throw new Zi;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=ra(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(!ea(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=aa(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(...ta(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;oa=d;let p=sa.length,m=t(s,c);oa=void 0;let ee=sa.length>p?sa.pop():void 0;return m instanceof Promise?m.then(e=>(ee&&(ee.issues=e.issues.length?ta(e.issues):$i),e)):(ee&&(ee.issues=m.issues.length?ta(m.issues):$i),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function la(){return ca}function ua(e,t){let n=e[Qi]?.backEdges;return n!==void 0&&ea(t)&&n.has(t)}let da=()=>{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 ${Ke(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 fa(){return{localeError:da()}}var pa,ma=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 ha(){return new ma}(pa=globalThis).__zod_globalRegistry??(pa.__zod_globalRegistry=ha());let ga=globalThis.__zod_globalRegistry;function _a(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
|
|
54
|
+
function va(e,t){return new e(_a({type:`string`,...g(t)}))}// @__NO_SIDE_EFFECTS__
|
|
55
|
+
function ya(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
56
|
+
function ba(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
57
|
+
function xa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
58
|
+
function Sa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
59
|
+
function Ca(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
60
|
+
function wa(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
61
|
+
function Ta(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
62
|
+
function Ea(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
63
|
+
function Da(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
64
|
+
function Oa(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
65
|
+
function ka(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
66
|
+
function Aa(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
67
|
+
function ja(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
68
|
+
function Ma(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
69
|
+
function Na(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
70
|
+
function Pa(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
71
|
+
function Fa(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
72
|
+
function Ia(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
73
|
+
function La(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
74
|
+
function Ra(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
75
|
+
function za(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
76
|
+
function Ba(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
77
|
+
function Va(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 Ha(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
79
|
+
function Ua(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
80
|
+
function Wa(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
81
|
+
function Ga(e,t){return new e(_a({type:`number`,checks:[],...g(t)}))}// @__NO_SIDE_EFFECTS__
|
|
82
|
+
function Ka(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
83
|
+
function qa(e,t){return new e({type:`boolean`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
84
|
+
function Ja(e,t){return new e({type:`null`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
85
|
+
function Ya(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
|
|
86
|
+
function Xa(e,t){return new e({type:`never`,...g(t)})}// @__NO_SIDE_EFFECTS__
|
|
87
|
+
function Za(e,t){return new Jn({check:`less_than`,...g(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
|
|
88
|
+
function Qa(e,t){return new Jn({check:`less_than`,...g(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
|
|
89
|
+
function $a(e,t){return new Yn({check:`greater_than`,...g(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
|
|
90
|
+
function eo(e,t){return new Yn({check:`greater_than`,...g(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
|
|
91
|
+
function to(e,t){return new Xn({check:`multiple_of`,...g(t),value:e})}// @__NO_SIDE_EFFECTS__
|
|
92
|
+
function no(e,t){return new Qn({check:`max_length`,...g(t),maximum:e})}// @__NO_SIDE_EFFECTS__
|
|
93
|
+
function ro(e,t){return new $n({check:`min_length`,...g(t),minimum:e})}// @__NO_SIDE_EFFECTS__
|
|
94
|
+
function io(e,t){return new er({check:`length_equals`,...g(t),length:e})}// @__NO_SIDE_EFFECTS__
|
|
95
|
+
function ao(e,t){return new nr({check:`string_format`,format:`regex`,...g(t),pattern:e})}// @__NO_SIDE_EFFECTS__
|
|
96
|
+
function oo(e){return new rr({check:`string_format`,format:`lowercase`,...g(e)})}// @__NO_SIDE_EFFECTS__
|
|
97
|
+
function so(e){return new ir({check:`string_format`,format:`uppercase`,...g(e)})}// @__NO_SIDE_EFFECTS__
|
|
98
|
+
function co(e,t){return new ar({check:`string_format`,format:`includes`,...g(t),includes:e})}// @__NO_SIDE_EFFECTS__
|
|
99
|
+
function lo(e,t){return new or({check:`string_format`,format:`starts_with`,...g(t),prefix:e})}// @__NO_SIDE_EFFECTS__
|
|
100
|
+
function uo(e,t){return new sr({check:`string_format`,format:`ends_with`,...g(t),suffix:e})}// @__NO_SIDE_EFFECTS__
|
|
101
|
+
function fo(e){return new cr({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
|
|
102
|
+
function po(e){return/* @__PURE__ */ fo(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
|
|
103
|
+
function mo(){return/* @__PURE__ */ fo(e=>e.trim())}// @__NO_SIDE_EFFECTS__
|
|
104
|
+
function ho(){return/* @__PURE__ */ fo(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
|
|
105
|
+
function go(){return/* @__PURE__ */ fo(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
|
|
106
|
+
function _o(){return/* @__PURE__ */ fo(e=>Ie(e))}// @__NO_SIDE_EFFECTS__
|
|
107
|
+
function vo(e,t,n){return new e({type:`array`,element:t,...g(n)})}// @__NO_SIDE_EFFECTS__
|
|
108
|
+
function yo(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 bo(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}// @__NO_SIDE_EFFECTS__
|
|
110
|
+
function xo(e,t){let n=/* @__PURE__ */ So(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 So(e,t){let n=new b({check:`custom`,...g(t)});return n._zod.check=e,n}function Co(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Oe(e,t,n[t]);return e}function wo(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??ga,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 To(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 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),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,C(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Co(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 Eo(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Do(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}/${Eo(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+Eo(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
112
112
|
|
|
113
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function ko(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;ko(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 Ao=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),jo=[`oneOf`,`anyOf`];function Mo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function No(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Ao.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]??Mo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ae(n,r,e.length===1?e[0]:No(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=Mo(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 Po(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Ao)if(t in e)return;let n=t.filter(e=>jo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=No(t);else{let e=n[0],i=jo.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=>No([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,wo(e,r))}function Fo(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)):wo(i,s),wo(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())ko(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)??[])Po(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)}wo(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:Lo(t,`input`,e.processors),output:Lo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function T(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return T(r.element,n);if(r.type===`set`)return T(r.valueType,n);if(r.type===`lazy`)return T(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return T(r.innerType,n);if(r.type===`intersection`)return T(r.left,n)||T(r.right,n);if(r.type===`record`||r.type===`map`)return T(r.keyType,n)||T(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:T(r.in,n)||T(r.out,n);if(r.type===`object`){for(let e in r.shape)if(T(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(T(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(T(e,n))return!0;return!!(r.rest&&T(r.rest,n))}return!1}let Io=(e,t={})=>n=>{let r=To({...n,processors:t});return w(e,r),Oo(r,e),Fo(r,e)},Lo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=To({...i??{},target:a,io:t,processors:n});return w(e,o),Oo(o,e),Fo(o,e)},Ro=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},zo=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Bo=(e,t)=>{Ro(e,`minimum`,t),zo(e,`maximum`,t)},Vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Ho=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Uo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Wo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Go=(e,t)=>Ro(e,`minimum`,t.minimum),Ko=(e,t)=>zo(e,`maximum`,t.maximum),qo=e=>(t,n)=>{Wo(t,n.format);let[r,i]=e[n.format];Ro(t,`minimum`,r),zo(t,`maximum`,i)},Jo={greater_than:(e,t)=>Ro(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>zo(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Vo(e,t.value),number_format:qo(Xe),bigint_format:qo(Ze),min_length:Go,max_length:Ko,length_equals:(e,t)=>Bo(e,t.length),min_size:Go,max_size:Ko,size_equals:(e,t)=>Bo(e,t.size),string_format:(e,t)=>{Wo(e,t.format),t.pattern&&Ho(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)=>Uo(e,t.mime)};function E(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Jo[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Ro(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Ro(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&zo(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&zo(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Uo(t,i.mime);for(let e of i.patterns??[])Ho(t,e);return t}let Yo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Xo=/* @__PURE__ */ new Map([[Kr,kn],[Jr,An]]),Zo=e=>Xo.get(e)??e,Qo=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=E(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Yo[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(Zo);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}))])}},$o=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=E(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):Eo(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}))])}},es=(e,t,n,r)=>{n.type=`boolean`},ts=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ns=(e,t,n,r)=>{n.not={}},rs=(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)},is=(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(Eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(Eo(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}},as=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},os=(e,t,n,r)=>{Eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},ss=(e,t,n,r)=>{Eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},cs=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=E(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=w(a.element,t,{...r,path:[...r.path,`items`]})};function ls(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?ls(t.out):t.type===`catch`?ls(t.innerType):e._zod.optin}let us=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ae(i.properties,e,w(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?ls(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=w(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},ds=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>w(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},fs=(e,t,n,r)=>{let i=e._zod.def,a=w(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=w(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},ps=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>w(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?w(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?ls(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=E(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function ms(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=ms(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=>ms(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`)?Hn:Vn).source)),p}let hs=/* @__PURE__ */ new WeakMap;function gs(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 hs.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=ms(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 _s=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=E(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=w(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ae(i.patternProperties,Zo(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=w(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=hs.get(t);n||(n=[],hs.set(t,n),t.deferred.push(()=>gs(t))),n.push(e)}i.additionalProperties=w(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&ls(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))}},vs=(e,t,n,r)=>{let i=e._zod.def,a=w(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},ys=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},bs=Symbol();function xs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),bs):JSON.parse(o)}let Ss=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=xs(i.defaultValue,e,t,n,r);o!==bs&&(n.default=o)},Cs=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=xs(i.defaultValue,e,t,n,r);o!==bs&&(n._prefault=o)},ws=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Ts=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;w(o,t,r);let s=t.seen.get(e);s.ref=o},Es=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Ds=(e,t,n,r)=>{let i=e._zod.def;w(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Os=(e,t,n,r)=>{let i=e._zod.innerType;w(i,t,r);let a=t.seen.get(e);a.ref=i},ks=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function As(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}let D=/*@__PURE__*/ y(`ZodError`,(e,t)=>{Ut.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);ks.has(n)||(ks.add(n),As(n,`format`,e=>t=>Kt(e,t)),As(n,`flatten`,e=>t=>Gt(e,t)),As(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),As(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}),js=/* @__PURE__ */ Jt(D),Ms=/* @__PURE__ */ Yt(D),Ns=/* @__PURE__ */ Xt(D),Ps=/* @__PURE__ */ Qt(D),Fs=/* @__PURE__ */ an(D),Is=/* @__PURE__ */ on(D),Ls=/* @__PURE__ */ sn(D),Rs=/* @__PURE__ */ cn(D),zs=/* @__PURE__ */ ln(D),Bs=/* @__PURE__ */ un(D),Vs=/* @__PURE__ */ dn(D),Hs=/* @__PURE__ */ fn(D);function Us(){b.localeError||It(pa())}function Ws(){b.memoizer||It({memoizer:ua()})}let O=/*@__PURE__*/ y(`ZodType`,(e,t)=>(Us(),S.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(h(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return qe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(dl(e,t))},superRefine(e,t){return this.check(fl(e,t))},overwrite(e){return this.check(/* @__PURE__ */ po(e))},optional(){return Hc(this)},exactOptional(){return Wc(this)},nullable(){return Kc(this)},nullish(){return Hc(Kc(this))},nonoptional(e){return Qc(this,e)},array(){return P(this)},or(e){return L([this,e])},and(e){return Nc(this,e)},transform(e){return nl(this,Bc(e))},default(e){return Jc(this,e)},prefault(e){return Xc(this,e)},catch(e){return el(this,e)},pipe(e){return nl(this,e)},readonly(){return il(this)},describe(e){let t=this.clone();return _a.add(t,{description:e}),t},meta(...e){if(e.length===0)return _a.get(this);let t=this.clone();return _a.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 bt(this,`~standard`,{...mr(this),jsonSchema:{input:Lo(this,`input`),output:Lo(this,`output`)}})},set"~standard"(e){yt(this,`~standard`,e)},parse:function e(t,n){return js(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Ms(this,t,n,{callee:e})},safeParse(e,t){return Ns(this,e,t)},async safeParseAsync(e,t){return Ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){yt(this,`spa`,e)},validate(e,t){return tn(this,e,t)},validateAsync(e,t){return rn(this,e,t)},encode:function e(t,n){return Fs(this,t,n,{callee:e})},decode:function e(t,n){return Is(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Ls(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Rs(this,t,n,{callee:e})},safeEncode(e,t){return zs(this,e,t)},safeDecode(e,t){return Bs(this,e,t)},async safeEncodeAsync(e,t){return Vs(this,e,t)},async safeDecodeAsync(e,t){return Hs(this,e,t)},toJSONSchema(e){return Io(this,{})(e)},get description(){return _a.get(this)?.description},get _def(){return this._zod.def}}),Gs=/*@__PURE__*/ y(`_ZodString`,(e,t)=>{hr.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qo(e,t,n,r)},/*@__PURE__*/ xt({format:e=>E(e).format??null,minLength:e=>E(e).minimum??null,maxLength:e=>E(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ oo(...e))},includes(...e){return this.check(/* @__PURE__ */ lo(...e))},startsWith(...e){return this.check(/* @__PURE__ */ uo(...e))},endsWith(...e){return this.check(/* @__PURE__ */ fo(...e))},min(...e){return this.check(/* @__PURE__ */ io(...e))},max(...e){return this.check(/* @__PURE__ */ ro(...e))},length(...e){return this.check(/* @__PURE__ */ ao(...e))},nonempty(...e){return this.check(/* @__PURE__ */ io(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ so(e))},uppercase(e){return this.check(/* @__PURE__ */ co(e))},trim(){return this.check(/* @__PURE__ */ ho())},normalize(...e){return this.check(/* @__PURE__ */ mo(...e))},toLowerCase(){return this.check(/* @__PURE__ */ go())},toUpperCase(){return this.check(/* @__PURE__ */ _o())},slugify(){return this.check(/* @__PURE__ */ vo())}})),Ks=/*@__PURE__*/ y(`ZodString`,(e,t)=>{hr.init(e,t),Gs.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ba(Zs,e))},url(e){return this.check(/* @__PURE__ */ Ea(nc,e))},jwt(e){return this.check(/* @__PURE__ */ Va(vc,e))},emoji(e){return this.check(/* @__PURE__ */ Da(ic,e))},guid(e){return this.check(/* @__PURE__ */ xa(Qs,e))},uuid(e){return this.check(/* @__PURE__ */ Sa($s,e))},uuidv4(e){return this.check(/* @__PURE__ */ Ca($s,e))},uuidv6(e){return this.check(/* @__PURE__ */ wa($s,e))},uuidv7(e){return this.check(/* @__PURE__ */ Ta($s,e))},nanoid(e){return this.check(/* @__PURE__ */ Oa(ac,e))},cuid(e){return this.check(/* @__PURE__ */ ka(oc,e))},cuid2(e){return this.check(/* @__PURE__ */ Aa(sc,e))},ulid(e){return this.check(/* @__PURE__ */ ja(cc,e))},base64(e){return this.check(/* @__PURE__ */ Ra(hc,e))},base64url(e){return this.check(/* @__PURE__ */ za(gc,e))},xid(e){return this.check(/* @__PURE__ */ Ma(lc,e))},ksuid(e){return this.check(/* @__PURE__ */ Na(uc,e))},ipv4(e){return this.check(/* @__PURE__ */ Pa(dc,e))},ipv6(e){return this.check(/* @__PURE__ */ Fa(fc,e))},cidrv4(e){return this.check(/* @__PURE__ */ Ia(pc,e))},cidrv6(e){return this.check(/* @__PURE__ */ La(mc,e))},e164(e){return this.check(/* @__PURE__ */ Ba(_c,e))},datetime(e){return this.check(/* @__PURE__ */ Ha(qs,e))},date(e){return this.check(/* @__PURE__ */ Ua(Js,e))},time(e){return this.check(/* @__PURE__ */ Wa(Ys,e))},duration(e){return this.check(/* @__PURE__ */ Ga(Xs,e))}});function k(e){return/* @__PURE__ */ ya(Ks,e)}let A=/*@__PURE__*/ y(`ZodStringFormat`,(e,t)=>{C.init(e,t),Gs.init(e,t)}),qs=/*@__PURE__*/ y(`ZodISODateTime`,(e,t)=>{Pr.init(e,t),A.init(e,t)}),Js=/*@__PURE__*/ y(`ZodISODate`,(e,t)=>{Fr.init(e,t),A.init(e,t)}),Ys=/*@__PURE__*/ y(`ZodISOTime`,(e,t)=>{Ir.init(e,t),A.init(e,t)}),Xs=/*@__PURE__*/ y(`ZodISODuration`,(e,t)=>{Lr.init(e,t),A.init(e,t)}),Zs=/*@__PURE__*/ y(`ZodEmail`,(e,t)=>{vr.init(e,t),A.init(e,t)}),Qs=/*@__PURE__*/ y(`ZodGUID`,(e,t)=>{gr.init(e,t),A.init(e,t)}),$s=/*@__PURE__*/ y(`ZodUUID`,(e,t)=>{_r.init(e,t),A.init(e,t)});function ec(e){return/* @__PURE__ */ Sa($s,e)}function tc(e){return/* @__PURE__ */ Ca($s,e)}let nc=/*@__PURE__*/ y(`ZodURL`,(e,t)=>{Er.init(e,t),A.init(e,t)});function rc(e){return/* @__PURE__ */ Ea(nc,e)}let ic=/*@__PURE__*/ y(`ZodEmoji`,(e,t)=>{Dr.init(e,t),A.init(e,t)}),ac=/*@__PURE__*/ y(`ZodNanoID`,(e,t)=>{Or.init(e,t),A.init(e,t)}),oc=/*@__PURE__*/ y(`ZodCUID`,(e,t)=>{kr.init(e,t),A.init(e,t)}),sc=/*@__PURE__*/ y(`ZodCUID2`,(e,t)=>{Ar.init(e,t),A.init(e,t)}),cc=/*@__PURE__*/ y(`ZodULID`,(e,t)=>{jr.init(e,t),A.init(e,t)}),lc=/*@__PURE__*/ y(`ZodXID`,(e,t)=>{Mr.init(e,t),A.init(e,t)}),uc=/*@__PURE__*/ y(`ZodKSUID`,(e,t)=>{Nr.init(e,t),A.init(e,t)}),dc=/*@__PURE__*/ y(`ZodIPv4`,(e,t)=>{Rr.init(e,t),A.init(e,t)}),fc=/*@__PURE__*/ y(`ZodIPv6`,(e,t)=>{Vr.init(e,t),A.init(e,t)}),pc=/*@__PURE__*/ y(`ZodCIDRv4`,(e,t)=>{Hr.init(e,t),A.init(e,t)}),mc=/*@__PURE__*/ y(`ZodCIDRv6`,(e,t)=>{Wr.init(e,t),A.init(e,t)}),hc=/*@__PURE__*/ y(`ZodBase64`,(e,t)=>{qr.init(e,t),A.init(e,t)}),gc=/*@__PURE__*/ y(`ZodBase64URL`,(e,t)=>{Xr.init(e,t),A.init(e,t)}),_c=/*@__PURE__*/ y(`ZodE164`,(e,t)=>{Zr.init(e,t),A.init(e,t)}),vc=/*@__PURE__*/ y(`ZodJWT`,(e,t)=>{$r.init(e,t),A.init(e,t)}),yc=/*@__PURE__*/ y(`ZodNumber`,(e,t)=>{ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ xt({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=E(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=E(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=E(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>E(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ eo(e,t))},gte(e,t){return this.check(/* @__PURE__ */ to(e,t))},min(e,t){return this.check(/* @__PURE__ */ to(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Qa(e,t))},lte(e,t){return this.check(/* @__PURE__ */ $a(e,t))},max(e,t){return this.check(/* @__PURE__ */ $a(e,t))},int(e){return this.check(M(e))},safe(e){return this.check(M(e))},positive(e){return this.check(/* @__PURE__ */ eo(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ to(0,e))},negative(e){return this.check(/* @__PURE__ */ Qa(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ $a(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ no(e,t))},step(e,t){return this.check(/* @__PURE__ */ no(e,t))},finite(){return this}}));function j(e){return/* @__PURE__ */ Ka(yc,e)}let bc=/*@__PURE__*/ y(`ZodNumberFormat`,(e,t)=>{ti.init(e,t),yc.init(e,t)});function M(e){return/* @__PURE__ */ qa(bc,e)}let xc=/*@__PURE__*/ y(`ZodBoolean`,(e,t)=>{ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r)});function N(e){return/* @__PURE__ */ Ja(xc,e)}let Sc=/*@__PURE__*/ y(`ZodNull`,(e,t)=>{ri.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r)});function Cc(e){return/* @__PURE__ */ Ya(Sc,e)}let wc=/*@__PURE__*/ y(`ZodUnknown`,(e,t)=>{ii.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Tc(){return/* @__PURE__ */ Xa(wc)}let Ec=/*@__PURE__*/ y(`ZodNever`,(e,t)=>{ai.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r)});function Dc(e){return/* @__PURE__ */ Za(Ec,e)}let Oc=/*@__PURE__*/ y(`ZodArray`,(e,t)=>{Ws(),li.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cs(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ io(e,t))},nonempty(e){return this.check(/* @__PURE__ */ io(1,e))},max(e,t){return this.check(/* @__PURE__ */ ro(e,t))},length(e,t){return this.check(/* @__PURE__ */ ao(e,t))},unwrap(){return this.element}});function P(e,t){return/* @__PURE__ */ yo(Oc,e,t)}let kc=/*@__PURE__*/ y(`ZodObject`,(e,t)=>{Ws(),hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>us(e,t,n,r),Dt(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return B(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(h(this._zod.def,{catchall:e}))},passthrough(){return this.clone(h(this._zod.def,{catchall:Tc()}))},loose(){return this.clone(h(this._zod.def,{catchall:Tc()}))},strict(){return this.clone(h(this._zod.def,{catchall:Dc()}))},strip(){return this.clone(h(this._zod.def,{catchall:void 0}))},extend(e){return tt(this,e)},safeExtend(e){return rt(this,e)},merge(e){return it(this,e)},pick(e){return Qe(this,e)},omit(e){return et(this,e)},partial(...e){return at(Vc,this,e[0])},exactPartial(...e){return at(Uc,this,e[0],`exactPartial`)},required(...e){return ot(Zc,this,e[0])}});function F(e,t){let n={type:`object`,shape:e??{},...g(t)};return new kc(n)}function I(e,t){return new kc({type:`object`,shape:e,catchall:Dc(),...g(t)})}let Ac=/*@__PURE__*/ y(`ZodUnion`,(e,t)=>{_i.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r),e.options=t.options});function L(e,t){return new Ac({type:`union`,options:e,...g(t)})}let jc=/*@__PURE__*/ y(`ZodDiscriminatedUnion`,(e,t)=>{Ac.init(e,t),yi.init(e,t)});function R(e,t,n){return new jc({type:`union`,options:t,discriminator:e,...g(n)})}let Mc=/*@__PURE__*/ y(`ZodIntersection`,(e,t)=>{bi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r)});function Nc(e,t){return new Mc({type:`intersection`,left:e,right:t})}let Pc=/*@__PURE__*/ y(`ZodTuple`,(e,t)=>{Ws(),Ci.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ps(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 Vc({type:`optional`,innerType:e}))})}});function Fc(e,t,n){let r=t instanceof S;return new Pc({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let Ic=/*@__PURE__*/ y(`ZodRecord`,(e,t)=>{Ws(),Di.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function z(e,t,n){return!t||!t._zod?new Ic({type:`record`,keyType:k(),valueType:e,...g(t)}):new Ic({type:`record`,keyType:e,valueType:t,...g(n)})}let Lc=/*@__PURE__*/ y(`ZodEnum`,(e,t)=>{Oi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(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 Lc({...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 Lc({...t,checks:[],...g(r),entries:i})}});function B(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Lc({type:`enum`,entries:n,...g(t)})}let Rc=/*@__PURE__*/ y(`ZodLiteral`,(e,t)=>{ki.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function V(e,t){return new Rc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let zc=/*@__PURE__*/ y(`ZodTransform`,(e,t)=>{Ws(),Ai.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ss(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ft(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(_t(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(_t(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Bc(e){return new zc({type:`transform`,transform:e})}let Vc=/*@__PURE__*/ y(`ZodOptional`,(e,t)=>{Mi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`optional`,innerType:e})}let Uc=/*@__PURE__*/ y(`ZodExactOptional`,(e,t)=>{Ni.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ds(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wc(e){return new Uc({type:`optional`,innerType:e})}let Gc=/*@__PURE__*/ y(`ZodNullable`,(e,t)=>{Pi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Kc(e){return new Gc({type:`nullable`,innerType:e})}let qc=/*@__PURE__*/ y(`ZodDefault`,(e,t)=>{Fi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ss(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Jc(e,t){return new qc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Yc=/*@__PURE__*/ y(`ZodPrefault`,(e,t)=>{Li.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xc(e,t){return new Yc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ue(t)}})}let Zc=/*@__PURE__*/ y(`ZodNonOptional`,(e,t)=>{Ri.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qc(e,t){return new Zc({type:`nonoptional`,innerType:e,...g(t)})}let $c=/*@__PURE__*/ y(`ZodCatch`,(e,t)=>{Vi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ws(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function el(e,t){return new $c({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Ot(t)})}let tl=/*@__PURE__*/ y(`ZodPipe`,(e,t)=>{Hi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ts(e,t,n,r),e.in=t.in,e.out=t.out});function nl(e,t){return new tl({type:`pipe`,in:e,out:t})}let rl=/*@__PURE__*/ y(`ZodReadonly`,(e,t)=>{Wi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function il(e){return new rl({type:`readonly`,innerType:e})}let al=/*@__PURE__*/ y(`ZodTemplateLiteral`,(e,t)=>{Ji.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r)});function ol(e,t){return new al({type:`template_literal`,parts:e,...g(t)})}let sl=/*@__PURE__*/ y(`ZodLazy`,(e,t)=>{Yi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function cl(e){return new sl({type:`lazy`,getter:e})}let ll=/*@__PURE__*/ y(`ZodCustom`,(e,t)=>{Xi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)});function ul(e,t){return/* @__PURE__ */ bo(ll,e??(()=>!0),t)}function dl(e,t={}){return/* @__PURE__ */ xo(ll,e,t)}function fl(e,t){return/* @__PURE__ */ So(e,t)}function pl(e){return/* @__PURE__ */ Ha(qs,e)}function ml(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 hl=L([k(),j(),N(),Cc()]);function gl(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 _l=ul(gl,{message:`JSON value must not contain circular references`}),vl=cl(()=>L([hl,P(vl),z(k(),vl)])),H=_l.pipe(vl);_l.pipe(P(vl));let yl=_l.pipe(z(k(),vl)),bl=I({code:k().min(1),message:k().min(1),retryable:N(),diagnostic:k().min(1).optional(),stage:k().min(1).optional(),durationMs:j().int().nonnegative().optional(),stderrTail:k().min(1).optional()}).superRefine(ml([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),xl=k().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),Sl=e=>k().min(1).max(e).refine(e=>e.trim().length>0),Cl=z(xl,F({label:Sl(256).optional(),description:Sl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),wl=z(xl,Sl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),Tl=k().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),U=Tl.brand(),W=Tl.brand(),El=Tl.brand();Tl.brand();let G=Tl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand();Tl.brand();let Dl=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),Ol=Dl.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),kl=F({modes:P(F({id:Ol,label:Dl.max(256),description:Dl.max(1024).optional(),dangerous:N().optional(),localizations:Cl.optional()}).strict()).min(1).max(32),defaultModeId:Ol}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});F({threadId:W,permissionModeId:Ol}).strict();let Al=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`});F({sourceThreadId:W,lastTurnId:El.optional(),targetHarnessId:U,targetModel:Al.max(1024).optional(),targetThinkingOptionId:Al.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).optional()}).strict();let jl=F({sourceThreadId:W,sourceHarnessId:U,sourceHarnessLabel:Al.max(256).optional(),sourceModel:Al.max(1024).optional(),targetHarnessId:U,targetHarnessLabel:Al.max(256).optional(),targetModel:Al.max(1024).optional(),totalTurns:j().int().min(1),boundaryTurnNumber:j().int().min(1),includedTurnNumbers:P(j().int().min(1)),omittedTurns:j().int().min(0),preview:k().max(32e3),createdAtMs:j().int().nonnegative()}).strict();F({threadId:W,handoff:jl}).strict();let Ml=k().regex(/^[a-z0-9][a-z0-9-]{0,63}$/u),Nl=k().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Role model must not contain control characters`),Pl=B([`stone`,`rose`,`mist`,`sage`,`amber`,`aqua`]),Fl=ol([`builtin:`,B([`pm-otter`,`frontend-otter`,`backend-otter`,`reviewer-otter`,`idea-otter`,`researcher-otter`,`writer-otter`,`architect-otter`,`debugger-otter`,`tester-otter`,`classic-otter`,`ops-otter`,`security-otter`,`audio-otter`,`scholar-otter`,`data-otter`,`advisor-otter`,`builder-otter`,`wizard-otter`,`sailor-otter`])]),Il=/^[a-zA-Z0-9_-]{1,64}\.(png|jpg|jpeg|webp)$/u,Ll=ol([`custom:`,k().regex(Il)]),Rl=ol([`catalog:`,k().regex(Il)]),zl=L([Fl,Ll]),Bl=L([Fl,Rl]),Vl=L([zl,Rl]),Hl=k().url().max(2048).refine(e=>/^https:\/\//i.test(e),`URL must use https://`),Ul=F({en:k().trim().min(1).max(2e3),"zh-CN":k().trim().min(1).max(2e3)}),Wl=F({slug:Ml,name:Ul,description:Ul,avatar:Bl,accentColor:Pl,recommendedHarnessId:U.optional(),author:k().trim().min(1).max(128),authorUrl:Hl.optional(),sourceUrl:Hl.optional(),license:k().trim().min(1).max(64).optional(),official:N().optional(),instructions:k().trim().min(1).max(1e5),updatedAt:pl()});F({formatVersion:V(1),generatedAt:pl(),roles:P(Wl)});let Gl=F({slug:Ml,name:k().refine(e=>e.trim().length>0),avatar:zl,accentColor:Pl}),Kl=Gl.readonly(),ql=Gl.extend({description:k(),harnessId:U,model:Nl.optional(),thinkingOptionId:G.optional(),instructions:k(),updatedAt:pl()});ql.omit({updatedAt:!0,avatar:!0}).extend({avatar:Vl}).partial({slug:!0}),F({locale:k().trim().min(1).max(64).optional()}),F({roles:P(ql)}),F({slug:Ml}),F({role:ql.nullable()}),F({role:ql}),F({deleted:N()}),F({refresh:N().optional()}),F({roles:P(Wl),fetchedAt:pl(),likes:z(Ml,j().int().nonnegative()).optional(),myLikes:z(Ml,j().int().min(0).max(5)).optional(),stale:N().optional(),error:k().optional()}),F({slug:Ml}),F({slug:Ml,likes:j().int().nonnegative(),myLikes:j().int().min(0).max(5),maxLikes:V(5),limitReached:N().optional()});let K=j().int().safe().nonnegative(),Jl=j().finite().nonnegative(),Yl=j().finite().min(0).max(100),Xl=F({version:L([V(3),V(4)]).optional(),requestId:k().min(1),turnId:k().min(1).max(1024),outputTokens:K,startedAtMs:K,completedAtMs:K}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Zl=F({version:L([V(2),V(3),V(4)]).optional(),value:Jl,turnId:k().min(1).max(1024),at:K}).strict();F({outputTimings:P(Xl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Zl.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Zl.extend({value:K}).optional()}).strict();let Ql=e=>wl.refine(t=>Object.values(t).every(t=>t.length<=e)),$l=F({composerIndicators:P(F({kind:V(`countdown`),id:k().min(1).max(64),expiresAtUnix:K,label:Ql(256).optional(),tooltip:Ql(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:Jl.optional(),sessionOutputTokensPerSecond:Jl.optional(),apiOutputTokensPerSecond:Jl.optional(),reasoningOutputTokens:K.optional(),totalTokens:K.optional(),totalCostUsd:Jl.optional(),totalCredits:Jl.optional(),contextUsagePercent:Jl.optional(),cacheHitRatePercent:Yl.optional(),contextWindowTokens:K.optional(),contextUsedTokens:K.optional(),planFiveHourUsedPercent:Yl.optional(),planFiveHourResetsAtUnix:K.optional(),planSevenDayUsedPercent:Yl.optional(),planSevenDayResetsAtUnix:K.optional(),sessionCacheHitRatePercent:Yl.optional(),timeToFirstOutputMs:K.optional(),latestRequestTimeToFirstOutputMs:K.optional(),costSource:B([`publicPrice`,`native`]).optional(),unpricedModels:P(k().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),eu=j().finite().min(0).max(100),tu=B([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),nu=F({id:k().min(1).max(256),label:k().min(1).max(256),localizations:Cl.optional()}).strict(),ru=F({product:k().min(1),periodType:tu.optional(),scope:nu.optional(),localizations:Cl.optional(),used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),usagePercent:eu,resetsAt:k().min(1).optional()}).strict(),iu=F({availableCount:j().int().safe().positive(),nextExpiresAt:k().min(1).optional(),expiresAt:P(k().min(1)).min(1).max(32).optional()}).strict(),au=F({used:j().finite().nonnegative().optional(),limit:j().finite().nonnegative().optional(),unit:k().min(1).max(32).optional(),label:k().min(1).optional(),scope:nu.optional(),localizations:Cl.optional(),usedPercent:eu,resetsAt:k().min(1).optional(),periodType:tu,productUsage:P(ru).min(1).optional(),resetCredits:iu.optional()}).strict(),ou=F({amount:j().finite().nonnegative(),currency:k().trim().min(1).max(8),label:k().trim().min(1).max(128).optional()}).strict();F({threadId:W,refresh:V(`exact`).optional()}).strict(),F({threadId:W,usage:$l.nullable(),accountCredits:au.optional(),accountBalance:ou.optional(),accountCreditsSupported:N().optional()}).strict();let su=k().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),cu=k().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),lu=B([`priority`,`ultrafast`]),q=F({id:cu,serviceTier:lu.optional()}).strict();function uu(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let du=su.max(256),fu=F({id:G,label:su.max(256)}).strict(),pu=F({ref:q,label:su.max(256),resolvedModelLabel:du.optional(),fastModel:q.optional(),supportedThinkingOptionIds:P(G).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 mu(e,t){if(t)return e?.models.find(e=>uu(e.ref,t)||uu(e.fastModel,t))}let hu=P(fu).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)}),gu=B([`catalog`,`activeModel`]),_u=F({models:P(pu),defaultModel:q.optional(),thinkingOptions:hu,defaultThinkingOptionId:G.optional(),thinkingOptionsScope:gu.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=>uu(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=>uu(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&&!mu(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`]})}),vu=F({fork:N(),forkAcrossCwd:N(),rollbackLastTurn:N()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),yu=B([`live`,`atCreate`]),bu=F({configuration:F({selectModel:N(),selectThinkingOption:N(),selectPermissionMode:N(),permissionModeScope:yu.default(`live`)}).strict(),history:vu,subagents:F({observe:N(),readTranscript:N()}).strict().optional(),autonomousTurns:F({observe:N()}).strict().optional(),steer:N().optional(),persistentPlan:N().optional()}).strict();F({effectiveModel:q.optional(),resolvedModelLabel:du.optional(),effectiveThinkingOptionId:G.optional(),availableThinkingOptions:hu.optional(),effectivePermissionModeId:Ol.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 xu=F({open:V(!0)}).strict();L([F({status:V(`ready`),catalog:_u,permissionModes:kl.optional(),capabilities:bu,webUi:xu.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),F({status:B([`notInstalled`,`unavailable`,`error`]),error:bl}).strict()]),F({harnessId:U,cwd:su.max(16384).optional(),refresh:N().optional(),purpose:V(`availability`).optional(),credentialAccess:B([`allow`,`retry`]).optional()}).strict(),F({harnessId:U}).strict(),F({}).strict(),F({threadId:W,model:q}).strict(),F({threadId:W,thinkingOptionId:G}).strict(),F({threadId:W,includeReferenceCapability:N().optional()}).strict(),R(`owner`,[F({owner:V(`codex`),locked:N(),effectiveModel:q.optional(),resolvedModelLabel:du.optional(),effectiveThinkingOptionId:G.optional(),effectivePermissionModeId:Ol.optional(),history:vu.optional(),supportsThreadReferences:V(!0).optional(),handoff:jl.optional(),roleSnapshot:Kl.optional(),nativeSessionRef:Dc().optional()}),F({owner:V(`external`),harnessId:su.max(256),transportModelId:su.max(8192),effectiveModel:q.optional(),resolvedModelLabel:du.optional(),effectiveThinkingOptionId:G.optional(),availableThinkingOptions:hu.optional(),effectivePermissionModeId:Ol.optional(),catalog:_u.optional(),history:vu,usage:$l.optional(),handoff:jl.optional(),roleSnapshot:Kl.optional(),nativeSessionRef:Dc().optional(),locked:V(!0)})]),F({threadIds:P(W).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let Su=R(`owner`,[F({threadId:W,owner:V(`codex`)}).strict(),F({threadId:W,owner:V(`external`),harnessId:k().max(256).pipe(U)}).strict()]);F({threads:P(Su).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),F({threadId:W,text:k().optional()}).strict(),F({kind:V(`application`),value:k().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),At}}).pipe(F({expectedTurnId:El,clientUserMessageId:k().min(1),delivery:B([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),B([`activeTurn`,`newTurn`]),F({delivery:B([`official`,`activeTurn`,`newTurn`])}).strict();let Cu=k().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),wu=Cu.pipe(U),Tu=wu.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Eu=k().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),Du=rc().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),Ou=F({en:k().max(4096),"zh-CN":k().max(4096).optional()}).strict(),ku=F({commands:P(F({terminal:k().max(256),command:k().max(4096)}).strict()).max(8),before:Ou.optional(),after:Ou.optional(),downloads:P(F({label:k().max(128),url:Du}).strict()).max(8).optional()}).strict(),Au={id:wu,name:k().trim().min(1).max(128),version:k().min(1).max(128),kind:V(`usage`).optional(),iconStyle:F({vector:F({viewBox:k().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:P(F({d:k().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:B([`evenodd`,`nonzero`]).optional(),fill:k().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:k().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:j().min(0).max(50).optional(),paddingRatio:j().min(0).max(.25).optional()}).strict().optional(),installation:ku.optional(),notice:Ou.optional(),launchCommand:V(!0).optional(),links:F({website:Du.optional(),documentation:Du.optional(),installation:Du.optional()}).strict().optional()};F({manifestVersion:V(1),...Au,adapterApiVersion:j().int().positive(),entry:Eu,icon:Eu.optional()}).strict();let ju=k().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),Mu=F({...Au,icon:ju.optional()}).strict();F({}).strict(),F({plugins:P(Mu.extend({id:Tu})).max(128)}).strict(),F({version:V(1),enabled:P(wu).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let Nu=131072,Pu=524288,Fu=Cu,Iu=B([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),Lu=B([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),Ru=k().trim().min(1).max(128);function zu(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 Bu=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),Vu=Eu.refine(e=>zu(e)!==void 0&&Bu(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),Hu=k().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(rc({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 Uu(e){return I({en:e,"zh-CN":e})}let Wu=Uu(k().trim().min(1)),Gu=P(Lu).max(Lu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),Ku=P(Iu).max(Iu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),qu={key:k().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:Wu,description:Wu.optional()},Ju={...qu,step:j().positive().optional(),default:j().optional()},Yu=I({value:k(),label:Wu}),Xu=R(`type`,[I({...qu,type:V(`boolean`),default:N().optional()}),I({...qu,type:V(`string`),placeholder:Wu.optional(),default:k().optional()}),I({...Ju,type:V(`number`),min:j().optional(),max:j().optional()}),I({...Ju,type:V(`range`),min:j(),max:j()}),I({...qu,type:V(`select`),options:P(Yu).min(1),default:k().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),Zu=F({manifestVersion:M().positive(),id:Fu,name:L([Ru,Uu(Ru)]),version:k().min(1).max(128),desktopApi:M().positive()}).passthrough().extend({manifestVersion:V(1),desktopApi:V(1),description:I({en:k().max(4096),"zh-CN":k().max(4096).optional()}).optional(),author:k().trim().min(1).max(128).optional(),repository:Hu.optional(),details:I({en:k().max(16384),"zh-CN":k().max(16384).optional()}).optional(),icon:Vu.optional(),screenshots:P(Vu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:I({script:Eu,style:Eu.optional()}).optional(),backend:I({script:Eu.refine(Bu)}).optional(),slots:Ku.default(()=>[]),settingsSchema:P(Xu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:Gu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),Qu=k().regex(/^[a-f0-9]{64}$/u),$u=I({state:B([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:Qu.optional(),error:k().optional(),conflictWith:Fu.optional()});I({controllerPid:M().positive(),targetId:k().nullable(),updatedAt:pl(),handledReloadToken:ec().optional(),extensions:z(k(),$u),surfaces:z(k(),$u).optional()});let ed=B([`official`,`community`]);function td(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let nd=Hu.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||td(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`),rd=I({id:Fu,version:k().trim().min(1).max(128),name:Wu.extend({en:Ru,"zh-CN":Ru}),description:Uu(k().trim().min(1).max(4096)),details:Uu(k().trim().min(1).max(16384)).optional(),author:k().trim().min(1).max(128),repository:Hu,stars:j().int().min(0).optional(),downloads:j().int().min(0).optional(),categories:Gu.optional(),trustTier:ed.default(`community`),icon:Hu.optional(),screenshots:P(Hu).max(4).optional(),downloadUrl:nd,sha256:Qu,slots:Ku.optional(),publishedAt:k().optional(),updatedAt:k().optional(),minCodexHostVersion:k().optional()});I({schemaVersion:V(1),generatedAt:k(),extensions:P(rd).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let id=k().trim().min(1).max(128),ad=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,od=Fu.refine(e=>!ad.test(e),`Reserved extension ID`),sd=B([`desktop`,`web`]),cd=Qu,ld=ec(),ud=Eu.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!ad.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),dd=Zu.shape,fd=(e,t=0)=>I({en:k().trim().min(t).max(e),"zh-CN":k().trim().min(t).max(e)}),pd=e=>ud.refine(t=>t.endsWith(e),`Expected a ${e} file`),md=pd(`.mjs`),hd=pd(`.css`).optional(),gd=e=>e.normalize(`NFC`).toLowerCase(),_d=I({manifestVersion:V(2),id:od,name:fd(128,1),version:k().trim().min(1).max(128),description:fd(4096),details:fd(16384).optional(),author:dd.author,repository:dd.repository,icon:dd.icon.refine(e=>e===void 0||ud.safeParse(e).success),screenshots:dd.screenshots.refine(e=>e===void 0||e.every(e=>ud.safeParse(e).success)),categories:dd.categories,settingsSchema:dd.settingsSchema,slots:dd.slots.removeDefault().optional(),page:I({apiVersion:V(1),entry:md,style:hd,title:fd(128,1).optional()}).optional(),widget:I({apiVersion:V(1),entry:md,style:hd}).optional(),desktop:I({apiVersion:V(1),script:pd(`.js`),style:hd}).optional(),web:I({apiVersion:V(1),entry:md.optional(),style:hd}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:I({apiVersion:V(1),entry:md}).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||gd(e)!==gd(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function vd({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 yd=id,bd=B([`running`,`waiting`,`idle`,`unknown`]),xd=F({createdAtMs:j().int().nonnegative()}),Sd=I({sourceThreadId:W,createdAtMs:j().int().nonnegative()}),Cd=I({harnessId:U,title:k().optional(),status:bd,archived:N(),updatedAtMs:j().int().nonnegative().optional()}),wd=F({revision:M().nonnegative(),parents:z(W,W),delegations:z(W,xd).optional(),handoffs:z(W,Sd).optional(),nodes:z(W,Cd),truncated:N()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,handoffs:t,nodes:n})=>Object.entries(e).every(([e,t])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t))&&Object.entries(t??{}).every(([e,{sourceThreadId:t}])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t)),`Missing Thread tree node`).refine(({parents:e,delegations:t})=>Object.keys(t??{}).every(t=>Object.hasOwn(e,t)),`Delegation metadata requires a matching parent edge`),Td=k().min(1).max(128);I({});let Ed=I({subscriptionId:Td});I({}),Ed.extend({snapshot:wd});let Dd=M().nonnegative(),Od=I({revision:Dd,enabled:P(od).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});I({version:V(1),seeded:P(od).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});let kd=F({version:k().trim().min(1).max(128),publishedAt:k().trim().min(1).max(64).optional(),notes:k().trim().min(1).max(8192),url:Hu.optional()}),{downloadUrl:Ad,...jd}=rd.shape,Md=F({...jd,id:od,format:V(`codexhost`),targets:P(sd).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:I({page:M().positive().optional(),widget:M().positive().optional(),desktop:M().positive().optional(),web:M().positive().optional(),backend:M().positive().optional()}),downloadUrl:Ad.refine(e=>e.startsWith(`https://`),`Expected HTTPS`),featured:N().optional(),featuredOrder:M().nonnegative().optional(),changelog:P(kd).max(20).optional()}).refine(({targets:e,apis:t})=>{let n=vd({hasPage:!!t.page,hasWidget:!!t.widget,hasDesktop:!!t.desktop,hasWeb:!!t.web,hasBackend:!!t.backend});return e.length===n.length&&n.every(t=>e.includes(t))},`Catalog targets must match the declared APIs`);F({schemaVersion:V(2),generatedAt:k().min(1),extensions:P(Md).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:Hu,fetchedAt:pl(),cached:N(),stale:N().optional()});let Nd={id:od},Pd={...Nd,activationId:ld,digest:cd},Fd={...Nd,activationId:Pd.activationId.optional()},Id=k().min(1).max(4096).refine(e=>/^(?:\/|[a-z]:[/\\])/iu.test(e)&&!e.includes(`\0`)&&!e.split(/[/\\]/u).some(e=>e===`.`||e===`..`),`Expected an absolute local path without dot segments`),Ld=k().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function Rd(e){return k().max(4*Math.ceil(e/3)).refine(t=>{let n=t.endsWith(`==`)?2:+!!t.endsWith(`=`);return t.length%4==0&&t.length*3/4-n<=e&&/^[A-Za-z0-9+/]*={0,2}$/u.test(t)},`Expected bounded standard padded base64`)}let zd=I({type:V(`github`),repository:k().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Ld.optional(),tag:Ld.optional(),asset:k().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:ud.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),Bd=L([I({type:V(`catalog`),...Nd}),zd,I({type:V(`zip`),base64:Rd(67108864).min(4)}),I({type:V(`zip`),localZipPath:Id}),I({type:V(`localDir`),localDir:Id})]),Vd=R(`type`,[I({type:V(`catalog`),...Nd}),zd,I({type:V(`zip`)}),I({type:V(`localDir`)})]),Hd=I({...Pd,manifest:_d,installedAt:pl(),source:Vd.optional()}),Ud=e=>k().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),Wd={desktopConflictWith:od.optional()},Gd=B([`none`,`inactive`,`starting`,`running`,`failed`]),Kd=R(`state`,[Hd.extend({state:V(`valid`),enabled:N(),...Wd,iconDataUrl:Ud(Nu).optional(),screenshotDataUrls:P(Ud(Pu)).max(4).optional(),backendState:Gd.optional(),backendError:k().optional()}),I({state:B([`invalid`,`incompatible`]),id:k().min(1),enabled:N(),error:k()})]);I({revision:Dd,configuration:Od,diagnostics:P(k()),extensions:P(Kd)}),I({revision:Dd,extensions:P(Hd.extend({...Wd,settingsRevision:Dd})).max(64)});let J={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,catalogIcon:`codexhost/extensions/catalogIcon`,catalogScreenshot:`codexhost/extensions/catalogScreenshot`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`,threadTree:`codexhost/extensions/threadTree`},qd=Object.freeze(Object.values(J));new Set(qd),I({});let Jd={expectedRevision:Dd};I({...Nd,...Jd}),Hd.extend({replaced:N()}),R(`state`,[I({state:V(`saved`),configuration:Od}),I({state:V(`revision-conflict`),revision:Dd})]),I({...Fd,digest:Pd.digest.optional(),path:ud}),I({mimeType:k().min(1),base64:Rd(16777216),digest:Pd.digest}),I({mimeType:B([`image/png`,`image/jpeg`,`image/webp`]),base64:Rd(Nu)});let Yd=M().min(0).max(3);I({mimeType:B([`image/png`,`image/jpeg`,`image/webp`]),base64:Rd(Pu)}),I({settingsRevision:Dd,values:yl}),J.list,J.snapshot,J.catalog,I({forceRefresh:N().optional(),staleWhileRevalidate:N().optional()}),J.catalogIcon,I({...Nd}),J.catalogScreenshot,I({...Nd,index:Yd}),J.install,I({source:Bd}),J.update,I({...Nd,expectedDigest:Pd.digest,expectedActivationId:Pd.activationId.optional(),source:Bd.optional()}),J.enable,J.disable,J.uninstall,I({...Nd,removeData:N().optional(),expectedDigest:Pd.digest.optional()}),I({...Nd,removed:N()}),J.recover,I({expectedRevision:Jd.expectedRevision.optional()}),J.asset,J.settingsGet,I(Fd),J.settingsSet,I({...Fd,expectedSettingsRevision:Dd,values:yl}),J.backendInvoke,I({...Fd,method:yd,params:H.optional()}),I({result:H}),J.threadTree;let Xd=k().regex(/^remote:[A-Za-z0-9_-]{8,512}$/u),Zd=L([tc(),Xd]),Qd=tc(),$d=k().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u),ef=B([`none`,`last_speaker`,`all`]),tf=B([`active`,`muted`,`removed`]),nf=M().nonnegative(),Y=M().positive(),rf=Y.max(20),X=k().refine(e=>e.trim().length>0),af=pl(),of={handle:$d.optional(),displayName:X.optional(),note:k().optional()},sf=F({memberId:Qd,threadId:W,handle:$d,displayName:X,note:k().optional(),roleSlug:Ml.optional(),roleSnapshot:Kl.optional(),harnessId:U,status:tf,projectless:N().optional(),joinedAtSeq:nf,lastDeliveredSeq:nf,lastRosterVersion:nf,createdAt:af}),cf=F({workspaceRoot:X,outputDirectory:X}),lf=F({hostId:X,displayName:X,state:X.optional(),color:k().optional(),filePreview:N().optional()}),uf=F({roomId:Zd,title:X,defaultCwd:X,projectlessWorkspace:cf.optional(),unmentionedPolicy:ef.default(`none`),allowAgentMentions:N().default(!0),maxAgentHops:rf.default(5),lastSeq:nf,lastSpeakerMemberId:Qd.optional(),rosterVersion:nf,humanEpoch:nf,relayPaused:N(),pinned:N(),createdAt:af,updatedAt:af,members:P(sf),remote:lf.optional()}).superRefine(({members:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,{handle:i,status:a}]of e.entries())a!==`removed`&&(n.has(i)&&t.addIssue({code:`custom`,path:[`members`,r,`handle`],message:`Handle must be unique among non-removed members`}),n.add(i))}),df=F({kind:B([`image`,`file`]),attachmentId:X.max(256),name:X.max(256),path:X.max(4096),bytes:nf,mediaType:X.max(128).optional(),width:Y.optional(),height:Y.optional()}),ff=F({roomId:Zd,seq:Y,messageId:X,senderType:B([`user`,`agent`,`system`]),senderMemberId:Qd.optional(),senderHandle:$d.optional(),senderName:k().optional(),senderThreadId:W.optional(),sourceTurnId:X.optional(),replyToSeq:Y.optional(),content:k(),attachments:P(df).max(12).optional(),mentionedMemberIds:P(Qd),mentionAll:N().optional(),hopCount:nf,createdAt:af}),pf={...of,model:Nl.optional(),thinkingOptionId:G.optional(),worktree:N().optional()},mf=R(`kind`,[I({kind:V(`role`),roleSlug:Ml,...pf}),I({kind:V(`harness`),harnessId:U,...pf}),I({kind:V(`existing`),threadId:W,...of,includeRecentHistory:N().default(!0).optional()})]),hf={roomId:Zd},gf={...hf,memberId:Qd},_f={title:X.optional(),unmentionedPolicy:ef.optional(),allowAgentMentions:N().optional(),maxAgentHops:rf.optional()};I({}),F({rooms:P(uf)}),I({...hf,limit:Y.optional(),beforeSeq:Y.optional()}),F({room:uf.nullable(),messages:P(ff),hasMore:N()}),I({..._f,defaultCwd:X.optional(),members:P(mf)}),F({room:uf}),I({...hf,..._f,pinned:N().optional(),relayPaused:N().optional()}),I(hf),F({deleted:N()}),I({...hf,member:mf}),F({room:uf,member:sf}),I({...gf,...of,status:tf.optional()}),I(gf),I({...gf,threadId:W,redeliverFrom:Y.optional(),note:k().optional()}),I({...hf,memberId:Qd.optional(),memberHandle:$d.optional(),threadId:W,redeliverFrom:Y.optional(),note:k().optional()}).refine(e=>e.memberId!==void 0!=(e.memberHandle!==void 0),`Provide exactly one of memberId or memberHandle`),F({room:uf,member:sf,previousThreadId:W,awakened:N()});let vf=F({roomId:Zd,title:X,memberCount:nf,updatedAt:af,member:F({memberId:Qd,threadId:W,handle:$d,displayName:X,status:tf,harnessId:U,roleSlug:Ml.optional(),roleName:X.optional()}).optional()});I({threadId:W.optional()}),F({rooms:P(vf)}),I({...hf,content:k().max(64e3),attachments:P(df).max(12).optional(),replyToSeq:Y.optional(),targetMemberIds:P(Qd).optional(),mentionAll:N().optional(),notice:N().optional()}).superRefine((e,t)=>{e.notice===!0?(e.content.trim().length===0&&t.addIssue({code:`custom`,path:[`content`],message:`Notice content is required`}),e.content.length>2e3&&t.addIssue({code:`custom`,path:[`content`],message:`Notice content must be at most 2000 characters`}),((e.targetMemberIds?.length??0)>0||e.mentionAll===!0||(e.attachments?.length??0)>0)&&t.addIssue({code:`custom`,path:[`notice`],message:`System notices cannot target members or include attachments`})):e.content.trim().length===0&&(e.attachments?.length??0)===0&&t.addIssue({code:`custom`,path:[`content`],message:`Message content or at least one attachment is required`})}),F({room:uf,message:ff,awakenedMemberIds:P(Qd)}),I({...hf,fromSeq:Y.optional(),toSeq:Y.optional(),limit:Y.optional()}),F({...hf,messages:P(ff),totalSeq:nf}),I({cwd:X,roomId:Zd.optional()}),F({isGitRepo:N()}),F({threadId:W}).strict(),F({confirmed:N()}).strict();let yf=[`codex-desktop`,`web`,`web-desktop-shell`,`web-mobile`,`ssh-remote`,`cli`],bf=[`darwin`,`win32`,`linux`],xf=[`arm64`,`x64`,`ia32`,`arm`],Sf=[`zh`,`en`,`ja`,`ko`,`de`,`fr`,`es`,`pt`,`ru`,`other`],Cf=[`codex`,`claude-code`,`antigravity`,`pi`,`opencode`,`cursor-cli`,`deepseek-harness`,`grok`,`omp`,`qwen-code`,`kiro-cli`,`codebuddy`,`workbuddy`,`workbuddy-cn`,`devin`,`hermes`,`qoder`,`qoder-cn`,`kimi-code`,`zcode`,`copilot`,`custom`],wf=[`official-relay`,`self-hosted-relay`,`tailscale-serve`,`tailscale-funnel`,`tailscale-ip`,`lan`,`custom-proxy`,`remote-peer`],Tf=k().min(1).max(40).regex(/^[0-9A-Za-z._+-]+$/u),Ef=B(yf),Df=B(Sf),Of=B(Cf),kf=B(wf);new Set(Cf),new Set(Sf),F({enabled:N(),forcedOffByEnv:N()}).strict(),F({enabled:N()}).strict(),F({surfaces:P(Ef).max(12).optional(),harnesses:P(Of).max(32).optional(),remoteAccess:P(kf).max(12).optional()}).strict(),F({dailyActive:V(!0).optional(),weeklyActive:V(!0).optional(),monthlyActive:V(!0).optional(),newInstall:V(!0).optional(),retainedD1:V(!0).optional(),retainedD7:V(!0).optional(),remoteAny:V(!0).optional(),appVersion:Tf.optional(),codexDesktopVersion:Tf.optional(),os:B(bf).optional(),arch:B(xf).optional(),uiLanguage:Df.optional(),surfaces:P(Ef).min(1).max(12).optional(),harnesses:P(Of).min(1).max(32).optional(),remoteAccess:P(kf).min(1).max(12).optional()}).strict().refine(e=>Object.keys(e).length>0,{message:`Telemetry heartbeat must contain at least one countable field`});let Af=4e3,jf={threadId:W};R(`action`,[I({...jf,action:B([`get`,`pause`,`resume`,`clear`])}),I({...jf,action:B([`create`,`edit`]),objective:k().trim().min(1).refine(e=>Array.from(e).length<=Af,`A goal objective can have up to ${Af} characters.`)})]),F({goal:F({threadId:W,objective:k(),status:B([`active`,`paused`,`blocked`,`usageLimited`,`budgetLimited`,`complete`]),tokenBudget:M().positive().nullable().default(null),tokensUsed:M().nonnegative(),timeUsedSeconds:M().nonnegative()}).nullable()});let Mf=k().trim().min(1),Nf=k().min(1),Pf=F({icon:k().nullable(),color:k().nullable()}),Ff=Pf.nullable(),If={create:{method:`codexhost/thread/sections/create`,params:F({name:Mf}).strict()},update:{method:`codexhost/thread/sections/update`,params:F({sectionId:Nf,name:Mf,appearance:Pf.strict().nullable().optional()}).strict()},delete:{method:`codexhost/thread/sections/delete`,params:F({sectionId:Nf}).strict()}};R(`status`,[F({status:V(`unknown`)}),F({status:V(`confirmed`),sectionId:Nf,section:F({id:Nf,name:k().min(1),appearance:Ff}).nullable(),syncPending:N()})]),[If.create.method,If.update.method,If.delete.method,...qd],F({threadSectionsV1:V(!0).optional(),complete:V(!1).optional(),sections:P(F({id:k().min(1),name:k().min(1),appearance:Ff.optional(),threads:P(yl)}))}),F({threadId:k().min(1).max(1024),sectionId:k().min(1).max(1024).nullable(),beforeThreadId:k().min(1).max(1024).nullable().optional(),expectedSourceSectionId:k().min(1).max(1024).optional()}).refine(e=>e.expectedSourceSectionId===void 0||e.sectionId===null),F({threadIds:P(k().min(1))}).strict(),F({threadId:k().min(1).max(1024),pinned:N()}).strict(),F({}).strict(),F({parents:z(k().min(1),k().min(1))}).strict(),F({prompt:k().max(16384).optional()}).strict(),F({projects:P(F({id:k(),name:k(),rootPaths:P(k()),createdAt:j().int().optional()})),nativeProjects:V(!0).optional(),assignments:z(k(),k()),projectless:P(k()),pinned:P(k()),sectionProjects:z(k(),P(k())).optional(),pinnedProjects:P(k()).optional()});let Lf=z(k(),Tc()),Rf=F({epoch:k().uuid(),sequence:j().int().nonnegative()});R(`type`,[F({type:V(`projects-changed`),cursor:Rf}),F({type:V(`skills-changed`),cursor:Rf,cwd:k().optional()}),F({type:V(`harness-inspection-changed`),cursor:Rf,harnessId:k().min(1)}),F({type:V(`display-settings-changed`),cursor:Rf}),F({type:V(`sections-changed`),cursor:Rf}),F({type:V(`groups-changed`),cursor:Rf,roomId:k().optional()}),F({type:V(`preferences-changed`),cursor:Rf,revision:j().int().nonnegative()}),F({type:V(`extensions-changed`),cursor:Rf,revision:Dd}),F({type:V(`hello`),version:V(1),cursor:Rf,reset:N()}),F({type:V(`changed`),cursor:Rf,threadId:k().min(1),method:k().min(1)})]);let zf=R(`type`,[F({type:V(`text`),id:k(),prompt:k(),secret:N().optional(),optional:N().optional()}),F({type:V(`choice`),id:k(),prompt:k(),multiple:N(),allowOther:N(),optional:N().optional(),options:P(F({value:k(),label:k(),description:k().optional()}))})]),Bf=R(`type`,[F({type:V(`approval`),title:k(),description:k().optional(),subject:Tc().optional(),actions:P(F({id:k(),label:k(),effect:k()}))}),F({type:V(`question`),title:k().optional(),questions:P(zf)})]),Vf=F({requestId:L([k(),j().int()]),threadId:k(),kind:B([`approval`,`question`]),interaction:Bf,request:Lf}),Hf=F({id:k().min(1),clientUserMessageId:k().min(1),input:P(Lf),presentationInput:P(Lf).nullable().optional()}).passthrough();F({fields:P(F({path:P(L([k(),j().int().nonnegative()])),originalLength:j().int().nonnegative()}))});let Uf=F({id:k().min(1),status:k().min(1),codexhostTurnOutcome:F({status:V(`unknown`),reason:k()}).optional(),items:P(F({id:k().min(1),type:k().min(1)}).passthrough()),codexhostFileOperations:P(F({beforeItemId:k().nullable(),item:F({id:k().min(1),type:k().min(1)}).passthrough()})).optional(),error:F({message:k().optional()}).passthrough().nullable().optional(),fingerprint:k().min(1).optional(),unchanged:V(!0).optional()}).passthrough(),Wf=F({id:k().min(1).max(512),fingerprint:k().min(1).max(128)});F({threadId:k().min(1),knownTurns:P(Wf).max(64).optional(),truncateToolOutput:N().optional()});let Gf=F({harnessId:k().min(1),nativeSessionId:k().min(1)});F({cursor:Rf,activeTurnId:k().min(1).nullable().optional(),command:F({name:k().min(1),turn:Uf,subsequentTurnId:k().min(1).optional()}).optional(),thread:F({id:k().min(1),cwd:k(),modelProvider:k().min(1),createdAt:j(),updatedAt:j(),recencyAt:j().nullable().optional(),status:F({type:k()}).passthrough(),name:k().nullable().optional(),preview:k().optional(),roleSnapshot:Kl.optional(),codexhostImportSource:Gf.optional(),turns:P(Uf).length(0)}).passthrough(),turnsPage:F({data:P(Uf).max(5),nextCursor:k().nullable()}),configuration:F({codexCollaborationMode:B([`plan`,`default`]).optional(),native:F({model:k().min(1).max(1024).optional(),reasoningEffort:k().min(1).max(128).optional()}).optional(),effectiveModel:q.optional(),effectiveThinkingOptionId:G.optional(),effectivePermissionModeId:Ol.optional()}),queue:F({items:P(Hf),pausedReason:B([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:P(Vf),handoff:jl.optional()}),F({version:V(1),owner:V(`service`).optional(),pid:j().int().positive(),port:j().int().min(1).max(65535),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j(),epoch:k().uuid(),capabilities:F({peerDelegation:V(1).optional(),threadReferenceContext:V(1).optional()}).optional()}),F({epoch:k().uuid(),threadId:k().min(1),requestId:L([k(),j().int()]),result:Lf}),F({includeArchived:N().optional(),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional(),scope:L([F({cwd:k().min(1).max(4096),excludeCwds:P(k().min(1).max(4096)).max(1024)}).strict(),F({projectId:k().min(1).max(1024),legacyThreadIds:P(k().min(1).max(1024)).max(1024),rootPaths:P(k().min(1).max(4096)).max(1024).optional()}).strict()]).optional()}).strict(),F({threads:P(yl),ownership:P(Su),archivedThreadIds:P(W),officialCursor:F({live:k().nullable(),archived:k().nullable().optional()}).strict().optional()}).strict(),Mu.pick({id:!0,name:!0,icon:!0,iconStyle:!0});let Kf=I({threadId:k().max(1024),title:k().max(240),project:k().max(240),harness:I({id:k().min(1).max(128),name:k().min(1).max(128)}).optional(),state:B([`idle`,`running`,`waiting`,`completed`,`failed`]),updatedAt:j().nonnegative()});I({epoch:k().max(128),revision:M().nonnegative(),running:M().nonnegative(),waiting:M().nonnegative(),sessions:P(Kf).max(32).default([]),notifications:P(I({threadId:k().max(1024),key:k().max(4096),kind:B([`completed`,`failed`,`approval`,`question`]),revision:M().nonnegative()})).max(256)});let qf=k().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);F({available:N()}).strict(),F({path:k().min(1),mimeType:qf}).strict();let Jf=B([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);R(`ok`,[F({ok:V(!0),text:k()}).strict(),F({ok:V(!1),error:F({code:Jf}).strict()}).strict()]),F({threadId:W.optional(),cwd:k().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let Yf=F({name:k().min(1).regex(/^[^\s[\]]+$/u),description:k().optional(),path:k().min(1),scope:B([`project`,`global`]),source:k().min(1)}).strict();F({revision:j().int().nonnegative(),complete:N(),skills:P(Yf),warnings:P(k()).optional()}).strict(),F({cwd:k().min(1).optional()}).strict();let Xf=F({kind:B([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:k().min(1)}).strict(),Zf=R(`status`,[F({status:V(`not-installed`)}),F({status:V(`not-running`)}),F({status:V(`not-logged-in`)}),F({status:V(`https-disabled`)}),F({status:V(`not-serving`),command:k()}),F({status:V(`occupied`),target:k()}),F({status:V(`serving`),url:k(),funnel:N()}),F({status:V(`error`),message:k()})]);F({state:Zf,error:k().optional()}).strict();let Qf=R(`status`,[F({status:V(`on`)}),F({status:V(`off`)}),F({status:V(`invalid`),reason:k()})]),$f=F({lan:N(),autostart:Qf}).strict(),ep=F({expiresAt:k().optional(),issuing:N(),failure:F({detail:k().optional(),retryAt:k(),paused:N()}).optional()}),tp=R(`status`,[F({status:V(`off`),reason:B([`invite`,`name-taken`,`banned`]).optional()}),F({status:V(`connecting`),reason:B([`full`,`unreachable`]).optional()}),F({status:V(`connected`),url:k(),certificate:ep}),F({status:V(`missing-certificate`),url:k(),certificate:ep}),F({status:V(`stopped`),reason:B([`replaced`,`rejected`,`unsupported-version`])})]);k().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),k().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let np=B([`official`,`self-hosted`]);F({secret:k().min(1),lastUsedAt:j().nullable(),networkUrls:P(Xf),directCandidates:P(Xf).optional(),tailscale:Zf,background:$f.optional(),relay:F({state:tp,enabled:N(),kind:np,officialHost:k(),customHost:k().optional(),officialHostname:k().optional(),customHostname:k().optional(),quotaUntil:k().optional()}).strict().optional()}).strict();let rp=I({threadId:k().min(1).max(1024),view:B([`result`,`messages`]),from:j().int().min(1).max(2**53-1).optional(),to:j().int().min(1).max(2**53-1).optional()}),ip=/^[a-zA-Z0-9_-]{1,64}$/u,Z=k().regex(ip),ap=k().regex(ip),op=k().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),sp=B([`relay`,`tailscale`,`lan`,`ssh`,`custom`]),cp=B([`auto`,`key`,`password`]);F({host:k().trim().min(1).max(255),port:j().int().min(1).max(65535).optional(),user:k().trim().min(1).max(128).optional(),identityFile:k().trim().min(1).max(1024).optional(),authMode:cp.default(`auto`),remoteDataDir:k().trim().min(1).max(1024).optional()});let lp=F({host:k().min(1).max(255),port:j().int().min(1).max(65535).optional(),user:k().min(1).max(128).optional(),authMode:cp,keyInstalled:N().optional()}),up=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],dp=B(up);new Set(up);let fp=B([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]),pp=F({peerId:Z,hostId:op,nodeId:ap.optional(),name:k().min(1).max(120),color:dp.optional(),origin:k().min(1).max(2048),transportKind:sp,ssh:lp.optional(),encrypted:N(),enabled:N(),state:fp,supportsPeerPairing:N().optional(),pairedBack:N().optional(),linkedPeerIds:P(Z).max(128).optional(),latencyMs:j().int().nonnegative().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),lastError:k().max(1e3).optional(),projectCount:j().int().nonnegative(),createdAt:k(),updatedAt:k()});F({localPlatform:k().max(64).optional(),peers:P(pp)}),F({connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),name:k().trim().min(1).max(120).optional(),color:dp.optional(),pairBack:N().optional(),meshPeerIds:P(Z).max(64).optional(),selfOrigin:k().min(1).max(2048).optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),I({origin:k().min(1).max(2048),token:k().min(1).max(2048),name:k().trim().min(1).max(120).optional(),color:dp.optional(),expectedNodeId:ap.optional()}),F({status:B([`added`,`updated`,`existing`]),peerId:Z,hostId:op,nodeId:ap.optional()});let mp=B([`added`,`updated`,`existing`,`failed`,`skipped`]);F({results:P(F({targetPeerId:Z,targetName:k().min(1).max(120),introducedHost:L([V(`local`),Z]),introducedName:k().min(1).max(120),status:mp,error:k().max(1e3).optional()}))}),F({peerIds:P(Z).max(64).optional(),includeSelf:N().optional(),includeMesh:N().optional(),selfOrigin:k().min(1).max(2048).optional()}),F({peerId:Z,name:k().trim().min(1).max(120).optional(),color:dp.nullable().optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional(),enabled:N().optional()}),F({peerId:Z}),F({removed:N()}),F({peerId:Z.optional(),connectionUrl:k().min(1).max(4096).optional(),origin:k().min(1).max(2048).optional(),token:k().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let hp=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});F({ok:N(),nodeId:ap.optional(),supportsPeerPairing:N().optional(),pairedBack:N().optional(),latencyMs:j().int().nonnegative().optional(),origin:k().max(2048).optional(),transportKind:sp.optional(),encrypted:N().optional(),version:k().max(128).optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional(),projectCount:j().int().nonnegative().optional(),projects:P(hp).optional(),error:k().max(1e3).optional()});let gp=F({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192),threadIds:P(k().min(1).max(1024))}),_p=F({attachments:V(1).optional(),workspaceFiles:V(1).optional(),officePreview:V(1).optional(),delegation:V(1).optional(),peerPairing:V(1).optional()}),vp=F({version:k().max(128),platform:k().max(64),hostname:k().max(255),homeDir:k().max(4096).optional(),epoch:k().min(1).max(256),nodeId:ap.optional(),peerNodes:z(op,ap).refine(e=>Object.keys(e).length<=128).optional(),projects:P(gp),capabilities:_p.optional()});I({threadId:k().min(1).max(1024),scope:k().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u).optional(),requestId:k().min(1).max(256).optional(),mode:B([`queue`,`steer`]).optional(),expectedTurnId:k().min(1).max(1024).nullable().optional(),content:P(R(`type`,[I({type:V(`text`),text:k()}),I({type:V(`file`),receiptId:k().min(1).max(128)})])).min(1).max(64)});let yp=F({ok:V(!1),error:F({code:k(),message:k(),details:z(k(),Tc()).optional()})});L([F({ok:V(!0),value:F({receiptId:k().min(1),file:F({attachmentId:k(),name:k(),bytes:j().int().nonnegative()})})}),yp]),L([F({ok:V(!0),value:F({accepted:V(!0)})}),yp]);let bp=F({name:k().min(1).max(512),path:k().min(1).max(8192),kind:V(`directory`)});F({peerId:Z,path:k().min(1).max(8192).optional()}),F({path:k().min(1).max(8192),parentPath:k().min(1).max(8192).nullable(),homeDir:k().min(1).max(8192).optional(),entries:P(bp)}),F({peerId:Z,parentPath:k().min(1).max(8192),name:k().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),F({path:k().min(1).max(8192),name:k().min(1).max(255)}),F({peerId:Z,path:k().min(1).max(8192),title:k().trim().min(1).max(255).optional()}),F({peerId:Z,workspaceId:k().min(1).max(1024),title:k().trim().min(1).max(255)}),F({peerId:Z,workspaceId:k().min(1).max(1024)}),F({workspaceId:k().min(1).max(1024).optional(),manifest:vp}),F({sessionHostId:k().min(1).max(128).optional()}),F({hosts:P(F({hostId:L([V(`local`),op]),name:k().min(1).max(120),isLocal:N().optional(),color:dp.optional(),hostname:k().max(255).optional()}))}),F({hostId:L([V(`local`),op])}),F({harnesses:P(F({id:k().regex(/^[a-z0-9][a-z0-9-]*$/u),name:k().min(1).max(120)}))}),F({hosts:P(F({alias:k().min(1).max(255),hostName:k().max(255).optional(),user:k().max(128).optional(),port:j().int().min(1).max(65535).optional(),identityFile:k().max(1024).optional()}))}),F({host:k().trim().min(1).max(255),port:j().int().min(1).max(65535).optional(),user:k().trim().min(1).max(128).optional(),identityFile:k().trim().min(1).max(1024).optional(),authMode:cp.default(`auto`),password:k().max(1024).optional(),installAuthorizedKey:N().optional(),name:k().trim().min(1).max(120).optional(),color:dp.optional(),remoteDataDir:k().trim().min(1).max(1024).optional(),sessionId:k().min(1).max(128).optional()}),F({ok:N(),codexhostInstalled:N(),version:k().max(128).optional(),nodeId:ap.optional(),platform:k().max(64).optional(),hostname:k().max(255).optional(),latencyMs:j().int().nonnegative().optional(),errorCode:k().max(128).optional(),error:k().max(1e3).optional()}),F({ok:N(),version:k().max(128).optional(),message:k().max(1e3).optional()}),F({promptId:k().min(1).max(128),sessionId:k().min(1).max(128).optional(),peerId:Z.optional(),host:k().min(1).max(255),kind:B([`host-key`,`password`,`passphrase`,`otp`,`generic`]),prompt:k().min(1).max(1e3),echo:N()}),F({promptId:k().min(1).max(128),sessionId:k().min(1).max(128).optional(),response:k().max(1024).optional(),cancel:N().optional()}),I({hostId:op,threadId:k().min(1).max(1024).optional()});let xp=B([`listHarnesses`,`inspect`,`start`,`send`,`cancel`,`read`,`answer`,`list`]);I({operation:xp,hopCount:j().int().min(0).max(16),sourceId:Z.optional(),input:yl});let Sp=I({code:k().min(1).max(128),message:k().max(4096),details:yl.optional()});L([I({ok:V(!0),value:H}),I({ok:V(!1),error:Sp})]);let Cp=I({id:k().min(1).max(1024),name:k().min(1).max(512),path:k().min(1).max(8192)});I({hosts:P(I({hostId:op,nodeId:ap.optional(),displayName:k().min(1).max(120),online:N(),state:fp,delegation:N(),projects:P(Cp),platform:k().max(64).optional(),hostname:k().max(255).optional(),homeDir:k().max(4096).optional()}))}),I({version:V(1),instanceId:k().min(1).max(128),pid:j().int().positive(),endpoint:k().min(1).max(256),token:k().regex(/^[0-9a-f]{64}$/u),startedAt:j().int().nonnegative()}),L([I({operation:V(`hosts`)}),I({operation:xp,hostId:op,hopCount:j().int().min(0).max(16),timeoutMs:j().int().min(1).max(12e4).optional(),input:yl})]);let wp=F({id:k().min(1).max(256),harnessId:k().min(1),label:k().min(1).max(512),provider:B([`openai-codex`,`xai`])}).strict(),Tp=k().regex(/^[a-z][a-z0-9-]{0,47}$/),Ep=F({name:Tp,source:wp,importedAt:k()}).strict(),Dp=R(`action`,[F({action:V(`list`)}).strict(),F({action:V(`import`),sourceId:k().min(1).max(256),name:Tp,confirmed:V(!0)}).strict(),F({action:V(`reimport`),sourceId:k().min(1).max(256),name:Tp,confirmed:V(!0)}).strict(),F({action:V(`remove`),name:Tp,confirmed:V(!0)}).strict()]),Op=F({provider:k().min(1).max(128),type:B([`oauth`,`api_key`,`unknown`]),label:k().min(1).max(512).optional(),vendor:B([`openai-codex`,`xai`]).optional()}).strict();F({sources:P(wp),targets:P(F({harnessId:k(),providers:P(B([`openai-codex`,`xai`])),imports:P(Ep),others:P(Op).default([])}).strict())}).strict(),F({targetHarnessId:k().min(1).max(128).optional(),request:Dp}).strict(),F({events:N()});let kp=P(I({agent:k().min(1).max(128),section:B([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);I({entries:kp.nullable()}),I({}),I({entries:kp,initializeOnly:N().optional()});let Ap=I({enabled:N(),timeoutMinutes:j().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let jp=k().regex(/^external$/u),Mp=U.transform(e=>String(e)),Np=I({model:q.optional(),thinkingOptionId:G.optional(),permissionModeId:Ol.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`);R(`mode`,[I({mode:V(`global`)}),I({mode:V(`last`)}),I({mode:V(`manual`),harnessId:U})]);let Pp=I({lastHarness:U.optional(),byHarness:z(Mp,Np)}),Fp=I({model:q.optional(),thinkingOptionId:G.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Ip=I({byHarness:z(Mp,Fp)}),Lp=k().min(1).max(1024),Rp=F({idleRelease:Ap.optional(),favorites:z(Mp,P(Lp).max(2048)).default({}),newThread:Pp.optional(),delegation:Ip.optional(),showGroupChatsInSidebar:N().optional()});I({scope:jp,revision:j().int().nonnegative(),values:Rp}),I({scope:jp.default(`external`)});let zp=R(`kind`,[I({kind:V(`idleRelease`),value:Ap}),I({kind:V(`favorite`),harnessId:U,modelId:Lp,enabled:N()}),I({kind:V(`favorites`),harnessId:U,modelIds:P(Lp).max(2048)}),I({kind:V(`newThread`),lastHarness:U.optional(),harnessId:U.optional(),configuration:Np.optional()}),I({kind:V(`delegation`),harnessId:U,configuration:Fp.nullable()}),I({kind:V(`groupChatsSidebar`),visible:N()})]);I({scope:jp.default(`external`),operations:P(zp).min(1).max(256),initializeOnly:N().optional(),expectedRevision:j().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),I({version:V(1),revision:j().int().nonnegative(),scopes:z(jp,Rp)});let Bp=j().finite().nonnegative(),Vp=I({input:Bp,output:Bp,cacheRead:Bp.optional(),cacheWrite:Bp.optional(),cacheWrite1h:Bp.optional()}),Hp=k().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);I({path:k(),entries:P(I({key:k(),price:Vp})),error:k().nullable()}),I({}),I({key:Hp,price:Vp.nullable(),previousKey:Hp.optional()}),I({model:Hp});let Up=I({official:N().optional(),canonicalModelId:k().min(1).optional(),provider:k().min(1).max(512),model:k().min(1).max(512),price:Vp});I({price:Vp.nullable(),suggestions:P(Up).max(6).optional()});let Wp=[`today`,`7d`,`30d`,`90d`,`all`],Q=j().int().min(0).max(2**53-1),Gp=k().regex(/^\d{4}-\d{2}-\d{2}$/u),Kp=k().min(1).max(128),qp=k().min(1).max(512),Jp=k().min(1).max(4096);I({range:B(Wp),timeZone:k().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:Kp.optional(),model:qp.nullable().optional(),project:Jp.nullable().optional(),date:Gp.optional()});let Yp=I({requests:Q,inputTokens:Q,cachedInputTokens:Q,cacheWriteInputTokens:Q,cacheKnownInputTokens:Q,cacheHitCachedInputTokens:Q,cacheHitInputTokens:Q,outputTokens:Q,reasoningOutputTokens:Q,costUsd:j().finite().min(0),unpricedRequests:Q,unmeteredRequests:Q}),Xp=Yp.shape,Zp=I({harness:Kp,sessionId:k().min(1).max(512),project:Jp.nullable(),title:k().min(1).max(200).optional(),models:P(qp).max(16),firstAtMs:Q,lastAtMs:Q,...Xp});I({range:B(Wp),from:Gp.nullable(),to:Gp,filters:I({harness:Kp.nullable(),model:qp.nullable(),unknownModel:N(),project:Jp.nullable(),unknownProject:N(),date:Gp.nullable()}),reading:I({complete:N(),sources:Q,read:Q}),failures:P(I({harness:Kp,message:k().max(2048)})).max(256),options:I({harnesses:P(Kp).max(256),models:P(qp.nullable()).max(4096),projects:P(Jp.nullable()).max(4096)}),modelLabels:P(I({harness:Kp,model:qp,label:qp})).max(4096).optional(),credits:P(I({harness:Kp,model:qp.nullable(),credits:j().finite().min(0),reportedRequests:Q,requests:Q})).max(4096).optional(),totals:Yp,daily:P(I({date:Gp,harness:Kp,...Xp})).max(2e5),hourly:P(I({weekday:j().int().min(0).max(6),hour:j().int().min(0).max(23),...Xp})).max(168),byHarness:P(I({harness:Kp,...Xp})).max(256),byModel:P(I({model:qp.nullable(),...Xp,harnessPricedRequests:Q})).max(4096),byProject:P(I({project:Jp.nullable(),...Xp})).max(4096),sessions:P(Zp).max(100),recentSessions:P(Zp).max(100).optional()}),F({threadId:W}),F({discarded:N()});let Qp=R(`type`,[F({id:k().min(1),type:V(`choice`),prompt:k(),options:P(F({value:k().min(1),label:k(),description:k().optional()})).min(1),multiple:N(),allowOther:N(),optional:N()}),F({id:k().min(1),type:V(`text`),prompt:k(),multiline:N(),secret:V(!1),optional:N(),placeholder:k().optional(),prefill:k().optional()})]),$p=F({interactionId:k().min(1),turnId:k().min(1),title:k().optional(),questions:P(Qp).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});I({threadId:k().min(1)}),F({questions:P($p)}),I({threadId:k().min(1),turnId:k().min(1),interactionId:k().min(1),answers:z(k(),P(k())),cancelled:N().default(!1)}),F({accepted:V(!0)});let em=`codexhostActiveTurnId`,tm=/* @__PURE__ */ new Set([em,`codexhostTurnChanges`,`codexhostToolOutput`,`codexGoal`]),nm=F({path:k(),oldText:k().nullable(),newText:k()});F({sessionId:k().min(1),turn:j().int().nonnegative(),path:k().min(1).optional()}),F({diffs:P(nm)}),I({}),I({}),F({reference:F({sessionId:k().min(1),epoch:k().min(1),turn:j().int().nonnegative(),seq:j().int().nonnegative(),callId:k().min(1),part:j().int().nonnegative(),version:k().min(1)}),length:j().int().nonnegative(),bytes:j().int().nonnegative()}),I({}),I({}),I({title:k().trim().min(1).max(200),type:B([`info`,`warning`,`danger`]),body:k().trim().min(1).max(16384)}),I({}),I({url:k().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status.codexhost/update/macos-signing/status.codexhost/update/macos-signing/setup.codexhost/update/macos-signing/remove`.split(`.`));let rm=B([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),im=B([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);I({threadId:k(),title:k(),harnessId:k(),state:rm,reason:im,inactiveMs:j().nonnegative()}),I({threadId:W,turnId:El});let am=F({email:k().trim().min(1).max(320).optional(),label:k().trim().min(1).max(256).optional(),plan:k().trim().min(1).max(128).optional(),credits:au.optional(),balance:ou.optional()}).strict();function om(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 sm=om(am),cm={harnessId:U,harnessName:k().trim().min(1).max(128)},lm=F(cm).strict();F({}).strict(),F({sources:P(lm).max(128)}).strict(),F({harnessId:U,refresh:N().optional()}).strict(),F({...cm,account:sm.nullable(),accounts:P(sm).max(8).optional()}).strict(),F({refresh:N().optional()}).strict(),F({accounts:P(om(am.extend(cm))).max(128)}).strict(),F({harnessId:Tu,model:q.optional(),thinkingOptionId:G.optional(),permissionModeId:Ol.optional(),prewarm:V(!0).optional()}).strict();let um=k().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);F({harnessId:Tu}).strict().extend({path:um.nullable()}),F({path:um.nullable(),restartRequired:N()}).strict(),F({harnessId:U,action:B([`check`,`update`,`install`]),confirmedVersion:k().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let dm=F({currentVersion:k().min(1).max(128),latestVersion:k().min(1).max(128),updateAvailable:N(),canUpdate:N(),latestVerifiedVersion:k().min(1).max(128).optional(),confirmationRequired:V(!0).optional(),versionKind:B([`cli`,`application`]).optional(),manualUpdateUrl:rc().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:k().max(2048).optional(),messageCode:k().min(1).max(128).optional(),notice:wl.optional(),latestVersionKind:B([`unknown`,`tracking-branch`]).optional()}).strict();F({taskId:k().uuid()}).strict(),R(`status`,[F({taskId:k().uuid(),status:V(`running`)}).strict(),F({taskId:k().uuid(),status:V(`succeeded`),result:dm}).strict(),F({taskId:k().uuid(),status:V(`failed`),error:F({code:j().int(),message:k().min(1).max(2048)}).strict()}).strict()]);let fm=k().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),pm=k().trim().min(1),mm=B([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),hm=F({accountId:fm,label:pm.max(256),email:k().email().max(320).optional(),planType:mm.optional()}).strict(),gm=B([`ready`,`unavailable`]);F({version:V(2),currentAccountId:fm.nullable(),phase:gm,revision:j().int().nonnegative(),instanceId:pm.max(1024).optional(),accounts:P(hm).max(1)}).strict(),F({accountId:fm,refresh:N().optional()}).strict(),F({accountId:fm,usage:$l.nullable(),accountCredits:au.optional(),freshness:B([`live`,`cached`]),observedAt:k().datetime().nullable()}).strict();let _m=1e3,vm=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),ym=vm.max(1024),bm=F({nativeSessionId:ym,title:vm.max(4096).nullable(),updatedAt:j().int().nonnegative().max(864e13),cwd:vm.max(16384),running:N().nullable()}).strict();F({}).strict(),F({harnesses:P(F({harnessId:Tu,name:vm.max(128)}).strict()).max(128)}).strict(),F({harnessId:Tu,query:k().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:j().int().nonnegative().safe().optional(),limit:j().int().min(1).max(_m).optional()}).strict(),F({candidates:P(bm).max(_m),total:j().int().nonnegative().safe()}).strict(),F({harnessId:Tu,nativeSessionId:ym}).strict(),F({threadId:vm.max(1024).pipe(W)}).strict();let xm=k().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Sm=ym,Cm=bm;F({}).strict(),F({candidates:P(Cm).max(1e3)}).strict(),F({nativeSessionId:Sm}).strict(),F({threadId:xm.max(1024).pipe(W)}).strict(),F({threadId:W,lastTurnId:El}).strict(),F({threadId:W}).strict();let wm=k().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();F({commands:P(F({id:wm,invocation:k().min(1).max(128),label:k().trim().min(1).max(128),description:k().trim().min(1).max(512).optional(),localizations:Cl.optional(),argumentMode:B([`none`,`text`]),kind:B([`command`,`skill`]).optional()}).strict()),warnings:P(k().min(1)).optional(),source:B([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),F({harnessId:U,cwd:k().min(1).optional()}).strict(),F({threadId:W}).strict(),F({threadId:W,commandId:wm,turnId:El.optional(),arguments:yl.optional()}).strict(),F({accepted:V(!0),turnId:El.optional()}).strict();let Tm=V(`2.0`).optional(),Em=Dc().optional(),Dm=k().min(1),Om=L([k(),j().int()]),km=F({code:j().int(),message:k(),data:H.optional()}).catchall(H).superRefine(ml([`data`]));L([F({jsonrpc:Tm,id:Om,method:Dm,params:H.optional(),result:Em,error:Em}).catchall(H).superRefine(ml([`jsonrpc`,`params`,`result`,`error`])),F({jsonrpc:Tm,id:Em,method:Dm,params:H.optional(),result:Em,error:Em}).catchall(H).superRefine(ml([`jsonrpc`,`id`,`params`,`result`,`error`])),F({jsonrpc:Tm,id:Om,method:Em,params:Em,result:H,error:Em}).catchall(H).superRefine(ml([`jsonrpc`,`method`,`params`,`error`])),F({jsonrpc:Tm,id:Om,method:Em,params:Em,result:Em,error:km}).catchall(H).superRefine(ml([`jsonrpc`,`method`,`params`,`result`]))]);let Am=k().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});I({harnessId:U,nativeSessionId:Am,locator:H.optional(),formatVersion:V(1)}).superRefine(ml([`locator`])),I({harnessId:U,nativeSessionId:Am,nativeTurnKey:Am,formatVersion:V(1)}),I({harnessId:U,nativeSessionId:Am,checkpointId:Am,locator:H.optional(),formatVersion:V(1)}).superRefine(ml([`locator`]));let jm=k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Mm=B([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Nm=B([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),Pm=I({completed:j().int().nonnegative(),total:j().int().positive()}).refine(e=>e.completed<=e.total,{path:[`completed`],message:`completed must not exceed total`}),Fm=I({version:jm,installation:Mm,phase:Nm,updatedAt:j().int().nonnegative(),downloadedBytes:j().int().nonnegative().optional(),totalBytes:j().int().positive().optional(),npmDownload:Pm.optional(),error:k().min(1).max(500).nullable(),serviceStopOutput:k().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});I({});let Im=k().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`),Lm=B([`idle`,`downloading`,`ready`,`failed`]),Rm=I({downloadedBytes:j().int().nonnegative(),totalBytes:j().int().positive()}).refine(e=>e.downloadedBytes<=e.totalBytes,{path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`});F({currentVersion:jm,installation:Mm.nullable(),latestVersion:jm.nullable(),updateAvailable:N(),installationAvailable:N(),releaseNotes:k().min(1).max(2e4).nullable(),releaseNotesUrl:Im.nullable(),status:Fm.nullable(),error:k().min(1).max(500).nullable(),stagedVersion:jm.nullable().optional(),backgroundPhase:Lm.optional(),backgroundDownload:Rm.nullable().optional(),backgroundError:k().min(1).max(500).nullable().optional(),runningTaskCount:j().int().nonnegative().optional()}),I({status:Fm}),I({status:Fm.nullable()}),I({supported:N(),enabled:N(),certificatePresent:N(),appSignedWithLocalCert:N(),appPath:k().min(1).nullable(),certificateName:k().min(1),certificateSha1:k().regex(/^[0-9A-Fa-f]{40}$/u).nullable()});let zm=I({icon:k().min(1).max(16).optional(),title:k().min(1).max(120),body:k().min(1).max(1200),contributors:P(k().min(1).max(39)).max(30)}),Bm=I({summary:k().min(1).max(600).optional(),themes:P(zm).min(1).max(12)}),Vm=I({version:jm,publishedAt:pl(),url:k().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Bm.nullable(),en:Bm.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});I({manual:N().optional()}),I({announcement:Vm.nullable(),unread:N()}),I({version:jm}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)(?:\?hostId=([^\s()<>"?#/&]+))?\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Hm=B([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);F({runningVersion:k().nullable(),installedVersion:k().nullable(),restartRequired:N(),remote:N(),updateSupported:N(),update:F({phase:Hm,targetVersion:k().nullable(),error:k().nullable()})});let Um=F({version:k().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();F({hostname:k().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),action:B([`inspect`,`install`,`update`,`restart`,`repair`,`uninstall`]),uninstallPackage:N().optional(),version:k().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),F({state:B([`installed`,`not-installed`])}).strict();let $=k().min(1).max(1024),Wm={hostId:$.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},Gm={...Wm,threadId:$},Km=k().min(1).max(8e3),qm={text:Km,requestId:$},Jm=P($).min(2).max(100).refine(e=>new Set(e).size===e.length,`Queued submission IDs must be distinct`);R(`accepted`,[F({accepted:V(!0),startQueuedItemId:$.optional()}),F({accepted:V(!1),code:B([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:k()})]),R(`available`,[F({available:V(!1)}),F({available:V(!0),canReorder:V(!0).optional(),items:P(F({id:$,clientUserMessageId:$,preview:k().max(801)})).max(100)})]);let Ym=R(`kind`,[I({kind:V(`hosts`)}),I({kind:V(`create`),...Wm,cwd:k().min(1).max(8192),epoch:$}),I({kind:V(`projectHarnesses`),...Wm,epoch:$}),I({kind:V(`inspectHarness`),...Wm,epoch:$,cwd:k().min(1).max(8192),harnessId:$}),I({kind:V(`startSelected`),...Wm,epoch:$,cwd:k().min(1).max(8192),harnessId:$,model:k().min(1).max(4096),serviceTier:B([`priority`,`ultrafast`]).optional(),reasoningEffort:$.optional()}),I({kind:V(`status`),...Gm}),I({kind:V(`list`),...Wm,cursor:k().nullable(),archived:N(),includeLoaded:V(!0).optional()}),I({kind:V(`read`),...Gm,page:I({cursor:k().min(1).max(8192).nullable(),epoch:$.optional(),sortDirection:B([`asc`,`desc`]).optional(),limit:j().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),I({kind:V(`usage`),...Gm,epoch:$}),I({kind:V(`configure`),...Gm,epoch:$,modelId:$.optional(),serviceTier:lu.optional(),thinkingOptionId:$.optional(),permissionModeId:$.optional()}).refine(e=>[e.modelId,e.thinkingOptionId,e.permissionModeId].filter(e=>e!==void 0).length===1,`Select exactly one remote setting`).refine(e=>e.serviceTier===void 0||e.modelId!==void 0,{message:`A service tier requires a Model ID`}),I({kind:V(`prompt`),...Gm,epoch:$,text:Km,requestId:$.optional()}),I({kind:V(`queue`),...Gm,epoch:$}),I({kind:V(`delivery`),...Gm,epoch:$,action:R(`kind`,[I({kind:V(`enqueue`),...qm}),I({kind:V(`steer`),...qm,turnId:$}),I({kind:V(`remove`),itemId:$}),I({kind:V(`reorder`),itemIds:Jm}),I({kind:V(`start`),itemId:$,onlyIfHead:V(!0).optional()}),I({kind:V(`sendNow`),itemId:$})])}),I({kind:V(`interrupt`),...Gm,epoch:$,turnId:$}),I({kind:V(`rename`),...Gm,epoch:$,name:k().min(1).max(512)}),I({kind:V(`archive`),...Gm,epoch:$,archived:N()}),I({kind:V(`respond`),...Gm,epoch:$,requestId:L([$,j().int()]),result:z(k(),Tc())})]),Xm=k().min(1).max(1024),Zm=F({hostId:Xm,displayName:k().min(1).max(1024),source:B([`codex-managed`,`discovered`]),sshAlias:k().max(1024).nullable(),sshHost:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable(),autoConnect:N(),connectionAnalyticsId:k().max(1024).optional()}),Qm=I({displayName:k().min(1).max(1024),hostname:k().min(1).max(1024),sshPort:j().int().min(1).max(65535).nullable(),identity:k().max(4096).nullable()});R(`action`,[I({action:V(`session`),operation:Ym}),I({action:V(`list`)}),I({action:V(`catalog`)}),I({action:V(`read-thread`),hostId:Xm.refine(e=>e!==`local`),input:rp}),I({action:V(`save`),draft:Qm,previous:Zm.nullable()}),I({action:V(`remove`),previous:Zm}),I({action:V(`connect`),hostId:Xm,enabled:N()}),I({action:V(`state`),hostId:Xm}),I({action:V(`runtime`),hostId:Xm}),I({action:V(`update`),hostId:Xm.refine(e=>e!==`local`),version:Um.shape.version})]),L([I({result:H}),I({error:I({code:j().int(),message:k()})})]),I({prompt:k().trim().min(1).max(2e3),cwd:k().max(4096).nullable()}),k().trim().min(1).max(60).nullable();let $m=k().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),eh=L([k(),F({en:k()}).catchall(k())]),th=F({title:eh.optional(),description:eh.optional(),icon:k().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:k().optional()});F({extensions:P(F({id:$m,name:k().min(1).max(214),version:k().min(1).max(128),format:V(`dsh`),supportedTargets:Fc([V(`web`)]),enabledTargets:P(V(`web`)).max(1),source:k().min(1).max(4096),projectUrl:k().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:k(),meta:th.optional(),loadError:k().optional()})),loadedIds:P($m),safeMode:N(),storeError:k().optional()});let nh=k().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);F({spec:k().trim().min(1).max(4096),registry:nh.optional()}).strict(),F({id:$m,enabled:N()}).strict(),F({id:$m}).strict(),V(1);function rh(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 Oo(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;Oo(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 ko=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Ao=[`oneOf`,`anyOf`];function jo(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Mo(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ko.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]??jo(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Oe(n,r,e.length===1?e[0]:Mo(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=jo(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 No(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ko)if(t in e)return;let n=t.filter(e=>Ao.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Mo(t);else{let e=n[0],i=Ao.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=>Mo([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Co(e,r))}function Po(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)):Co(i,s),Co(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())Oo(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)??[])No(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)}Co(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,Oe(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:Io(t,`input`,e.processors),output:Io(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`||r.type===`catch`)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 Fo=(e,t={})=>n=>{let r=wo({...n,processors:t});return C(e,r),Do(r,e),Po(r,e)},Io=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=wo({...i??{},target:a,io:t,processors:n});return C(e,o),Do(o,e),Po(o,e)},Lo=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Ro=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},zo=(e,t)=>{Lo(e,`minimum`,t),Ro(e,`maximum`,t)},Bo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Vo=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Ho=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Uo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Wo=(e,t)=>Lo(e,`minimum`,t.minimum),Go=(e,t)=>Ro(e,`maximum`,t.maximum),Ko=e=>(t,n)=>{Uo(t,n.format);let[r,i]=e[n.format];Lo(t,`minimum`,r),Ro(t,`maximum`,i)},qo={greater_than:(e,t)=>Lo(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>Ro(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Bo(e,t.value),number_format:Ko(Je),bigint_format:Ko(Ye),min_length:Wo,max_length:Go,length_equals:(e,t)=>zo(e,t.length),min_size:Wo,max_size:Go,size_equals:(e,t)=>zo(e,t.size),string_format:(e,t)=>{Uo(e,t.format),t.pattern&&Vo(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)=>Ho(e,t.mime)};function T(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)qo[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Lo(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Lo(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&Ro(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&Ro(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Bo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Ho(t,i.mime);for(let e of i.patterns??[])Vo(t,e);return t}let Jo={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Yo=/* @__PURE__ */ new Map([[Gr,On],[qr,kn]]),Xo=e=>Yo.get(e)??e,Zo=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=T(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Jo[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(Xo);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}=T(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)):To(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}))])}},$o=(e,t,n,r)=>{n.type=`boolean`},es=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},ts=(e,t,n,r)=>{n.not={}},ns=(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)},rs=(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(To(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(To(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}},is=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},as=(e,t,n,r)=>{To(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},os=(e,t,n,r)=>{To(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},ss=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=T(e);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`]})};function cs(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?cs(t.out):t.type===`catch`?cs(t.innerType):e._zod.optin}let ls=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&To(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Oe(i.properties,e,C(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`?cs(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=C(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},us=(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},ds=(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,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},fs=(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,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?cs(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}=T(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function ps(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=ps(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=>ps(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`)?Vn:Bn).source)),p}let ms=/* @__PURE__ */ new WeakMap;function hs(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 ms.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=ps(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 gs=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=T(o).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)Oe(i.patternProperties,Xo(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=C(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=ms.get(t);n||(n=[],ms.set(t,n),t.deferred.push(()=>hs(t))),n.push(e)}i.additionalProperties=C(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&cs(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))}},_s=(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`}]},vs=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ys=Symbol();function bs(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(To(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),ys):JSON.parse(o)}let xs=(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=bs(i.defaultValue,e,t,n,r);o!==ys&&(n.default=o)},Ss=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=bs(i.defaultValue,e,t,n,r);o!==ys&&(n._prefault=o)},Cs=(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{To(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},ws=(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},Ts=(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},Es=(e,t,n,r)=>{let i=e._zod.def;C(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ds=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function Os(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 E=/*@__PURE__*/ v(`ZodError`,(e,t)=>{Ht.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Ds.has(n)||(Ds.add(n),Os(n,`format`,e=>t=>Gt(e,t)),Os(n,`flatten`,e=>t=>Wt(e,t)),Os(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Se,2)}),Os(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}),ks=/* @__PURE__ */ qt(E),As=/* @__PURE__ */ Jt(E),js=/* @__PURE__ */ Yt(E),Ms=/* @__PURE__ */ Zt(E),Ns=/* @__PURE__ */ rn(E),Ps=/* @__PURE__ */ an(E),Fs=/* @__PURE__ */ on(E),Is=/* @__PURE__ */ sn(E),Ls=/* @__PURE__ */ cn(E),Rs=/* @__PURE__ */ ln(E),zs=/* @__PURE__ */ un(E),Bs=/* @__PURE__ */ dn(E);function Vs(){y.localeError||Ft(fa())}function Hs(){y.memoizer||Ft({memoizer:la()})}let D=/*@__PURE__*/ v(`ZodType`,(e,t)=>(Vs(),x.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 Ge(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(cl(e,t))},superRefine(e,t){return this.check(ll(e,t))},overwrite(e){return this.check(/* @__PURE__ */ fo(e))},optional(){return Bc(this)},exactOptional(){return Hc(this)},nullable(){return Wc(this)},nullish(){return Bc(Wc(this))},nonoptional(e){return Xc(this,e)},array(){return N(this)},or(e){return I([this,e])},and(e){return jc(this,e)},transform(e){return el(this,Rc(e))},default(e){return Kc(this,e)},prefault(e){return Jc(this,e)},catch(e){return Qc(this,e)},pipe(e){return el(this,e)},readonly(){return rl(this)},describe(e){let t=this.clone();return ga.add(t,{description:e}),t},meta(...e){if(e.length===0)return ga.get(this);let t=this.clone();return ga.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`,{...pr(this),jsonSchema:{input:Io(this,`input`),output:Io(this,`output`)}})},set"~standard"(e){vt(this,`~standard`,e)},parse:function e(t,n){return ks(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await As(this,t,n,{callee:e})},safeParse(e,t){return js(this,e,t)},async safeParseAsync(e,t){return Ms(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){vt(this,`spa`,e)},validate(e,t){return en(this,e,t)},validateAsync(e,t){return nn(this,e,t)},encode:function e(t,n){return Ns(this,t,n,{callee:e})},decode:function e(t,n){return Ps(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Fs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Is(this,t,n,{callee:e})},safeEncode(e,t){return Ls(this,e,t)},safeDecode(e,t){return Rs(this,e,t)},async safeEncodeAsync(e,t){return zs(this,e,t)},async safeDecodeAsync(e,t){return Bs(this,e,t)},toJSONSchema(e){return Fo(this,{})(e)},get description(){return ga.get(this)?.description},get _def(){return this._zod.def}}),Us=/*@__PURE__*/ v(`_ZodString`,(e,t)=>{mr.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r)},/*@__PURE__*/ bt({format:e=>T(e).format??null,minLength:e=>T(e).minimum??null,maxLength:e=>T(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ ao(...e))},includes(...e){return this.check(/* @__PURE__ */ co(...e))},startsWith(...e){return this.check(/* @__PURE__ */ lo(...e))},endsWith(...e){return this.check(/* @__PURE__ */ uo(...e))},min(...e){return this.check(/* @__PURE__ */ ro(...e))},max(...e){return this.check(/* @__PURE__ */ no(...e))},length(...e){return this.check(/* @__PURE__ */ io(...e))},nonempty(...e){return this.check(/* @__PURE__ */ ro(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ oo(e))},uppercase(e){return this.check(/* @__PURE__ */ so(e))},trim(){return this.check(/* @__PURE__ */ mo())},normalize(...e){return this.check(/* @__PURE__ */ po(...e))},toLowerCase(){return this.check(/* @__PURE__ */ ho())},toUpperCase(){return this.check(/* @__PURE__ */ go())},slugify(){return this.check(/* @__PURE__ */ _o())}})),Ws=/*@__PURE__*/ v(`ZodString`,(e,t)=>{mr.init(e,t),Us.init(e,t)},{email(e){return this.check(/* @__PURE__ */ ya(Ys,e))},url(e){return this.check(/* @__PURE__ */ Ta(ec,e))},jwt(e){return this.check(/* @__PURE__ */ Ba(gc,e))},emoji(e){return this.check(/* @__PURE__ */ Ea(nc,e))},guid(e){return this.check(/* @__PURE__ */ ba(Xs,e))},uuid(e){return this.check(/* @__PURE__ */ xa(Zs,e))},uuidv4(e){return this.check(/* @__PURE__ */ Sa(Zs,e))},uuidv6(e){return this.check(/* @__PURE__ */ Ca(Zs,e))},uuidv7(e){return this.check(/* @__PURE__ */ wa(Zs,e))},nanoid(e){return this.check(/* @__PURE__ */ Da(rc,e))},cuid(e){return this.check(/* @__PURE__ */ Oa(ic,e))},cuid2(e){return this.check(/* @__PURE__ */ ka(ac,e))},ulid(e){return this.check(/* @__PURE__ */ Aa(oc,e))},base64(e){return this.check(/* @__PURE__ */ La(pc,e))},base64url(e){return this.check(/* @__PURE__ */ Ra(mc,e))},xid(e){return this.check(/* @__PURE__ */ ja(sc,e))},ksuid(e){return this.check(/* @__PURE__ */ Ma(cc,e))},ipv4(e){return this.check(/* @__PURE__ */ Na(lc,e))},ipv6(e){return this.check(/* @__PURE__ */ Pa(uc,e))},cidrv4(e){return this.check(/* @__PURE__ */ Fa(dc,e))},cidrv6(e){return this.check(/* @__PURE__ */ Ia(fc,e))},e164(e){return this.check(/* @__PURE__ */ za(hc,e))},datetime(e){return this.check(/* @__PURE__ */ Va(Gs,e))},date(e){return this.check(/* @__PURE__ */ Ha(Ks,e))},time(e){return this.check(/* @__PURE__ */ Ua(qs,e))},duration(e){return this.check(/* @__PURE__ */ Wa(Js,e))}});function O(e){return/* @__PURE__ */ va(Ws,e)}let k=/*@__PURE__*/ v(`ZodStringFormat`,(e,t)=>{S.init(e,t),Us.init(e,t)}),Gs=/*@__PURE__*/ v(`ZodISODateTime`,(e,t)=>{Nr.init(e,t),k.init(e,t)}),Ks=/*@__PURE__*/ v(`ZodISODate`,(e,t)=>{Pr.init(e,t),k.init(e,t)}),qs=/*@__PURE__*/ v(`ZodISOTime`,(e,t)=>{Fr.init(e,t),k.init(e,t)}),Js=/*@__PURE__*/ v(`ZodISODuration`,(e,t)=>{Ir.init(e,t),k.init(e,t)}),Ys=/*@__PURE__*/ v(`ZodEmail`,(e,t)=>{_r.init(e,t),k.init(e,t)}),Xs=/*@__PURE__*/ v(`ZodGUID`,(e,t)=>{hr.init(e,t),k.init(e,t)}),Zs=/*@__PURE__*/ v(`ZodUUID`,(e,t)=>{gr.init(e,t),k.init(e,t)});function Qs(e){return/* @__PURE__ */ xa(Zs,e)}function $s(e){return/* @__PURE__ */ Sa(Zs,e)}let ec=/*@__PURE__*/ v(`ZodURL`,(e,t)=>{Tr.init(e,t),k.init(e,t)});function tc(e){return/* @__PURE__ */ Ta(ec,e)}let nc=/*@__PURE__*/ v(`ZodEmoji`,(e,t)=>{Er.init(e,t),k.init(e,t)}),rc=/*@__PURE__*/ v(`ZodNanoID`,(e,t)=>{Dr.init(e,t),k.init(e,t)}),ic=/*@__PURE__*/ v(`ZodCUID`,(e,t)=>{Or.init(e,t),k.init(e,t)}),ac=/*@__PURE__*/ v(`ZodCUID2`,(e,t)=>{kr.init(e,t),k.init(e,t)}),oc=/*@__PURE__*/ v(`ZodULID`,(e,t)=>{Ar.init(e,t),k.init(e,t)}),sc=/*@__PURE__*/ v(`ZodXID`,(e,t)=>{jr.init(e,t),k.init(e,t)}),cc=/*@__PURE__*/ v(`ZodKSUID`,(e,t)=>{Mr.init(e,t),k.init(e,t)}),lc=/*@__PURE__*/ v(`ZodIPv4`,(e,t)=>{Lr.init(e,t),k.init(e,t)}),uc=/*@__PURE__*/ v(`ZodIPv6`,(e,t)=>{Br.init(e,t),k.init(e,t)}),dc=/*@__PURE__*/ v(`ZodCIDRv4`,(e,t)=>{Vr.init(e,t),k.init(e,t)}),fc=/*@__PURE__*/ v(`ZodCIDRv6`,(e,t)=>{Ur.init(e,t),k.init(e,t)}),pc=/*@__PURE__*/ v(`ZodBase64`,(e,t)=>{Kr.init(e,t),k.init(e,t)}),mc=/*@__PURE__*/ v(`ZodBase64URL`,(e,t)=>{Yr.init(e,t),k.init(e,t)}),hc=/*@__PURE__*/ v(`ZodE164`,(e,t)=>{Xr.init(e,t),k.init(e,t)}),gc=/*@__PURE__*/ v(`ZodJWT`,(e,t)=>{Qr.init(e,t),k.init(e,t)}),_c=/*@__PURE__*/ v(`ZodNumber`,(e,t)=>{$r.init(e,t),D.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}=T(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=T(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=T(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>T(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ $a(e,t))},gte(e,t){return this.check(/* @__PURE__ */ eo(e,t))},min(e,t){return this.check(/* @__PURE__ */ eo(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Za(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(j(e))},safe(e){return this.check(j(e))},positive(e){return this.check(/* @__PURE__ */ $a(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ eo(0,e))},negative(e){return this.check(/* @__PURE__ */ Za(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ Qa(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ to(e,t))},step(e,t){return this.check(/* @__PURE__ */ to(e,t))},finite(){return this}}));function A(e){return/* @__PURE__ */ Ga(_c,e)}let vc=/*@__PURE__*/ v(`ZodNumberFormat`,(e,t)=>{ei.init(e,t),_c.init(e,t)});function j(e){return/* @__PURE__ */ Ka(vc,e)}let yc=/*@__PURE__*/ v(`ZodBoolean`,(e,t)=>{ti.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$o(e,t,n,r)});function M(e){return/* @__PURE__ */ qa(yc,e)}let bc=/*@__PURE__*/ v(`ZodNull`,(e,t)=>{ni.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r)});function xc(e){return/* @__PURE__ */ Ja(bc,e)}let Sc=/*@__PURE__*/ v(`ZodUnknown`,(e,t)=>{ri.init(e,t),D.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Cc(){return/* @__PURE__ */ Ya(Sc)}let wc=/*@__PURE__*/ v(`ZodNever`,(e,t)=>{ii.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r)});function Tc(e){return/* @__PURE__ */ Xa(wc,e)}let Ec=/*@__PURE__*/ v(`ZodArray`,(e,t)=>{Hs(),ci.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ss(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ ro(e,t))},nonempty(e){return this.check(/* @__PURE__ */ ro(1,e))},max(e,t){return this.check(/* @__PURE__ */ no(e,t))},length(e,t){return this.check(/* @__PURE__ */ io(e,t))},unwrap(){return this.element}});function N(e,t){return/* @__PURE__ */ vo(Ec,e,t)}let Dc=/*@__PURE__*/ v(`ZodObject`,(e,t)=>{Hs(),mi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ls(e,t,n,r),Et(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return z(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:Cc()}))},loose(){return this.clone(h(this._zod.def,{catchall:Cc()}))},strict(){return this.clone(h(this._zod.def,{catchall:Tc()}))},strip(){return this.clone(h(this._zod.def,{catchall:void 0}))},extend(e){return $e(this,e)},safeExtend(e){return tt(this,e)},merge(e){return nt(this,e)},pick(e){return Xe(this,e)},omit(e){return Qe(this,e)},partial(...e){return rt(zc,this,e[0])},exactPartial(...e){return rt(Vc,this,e[0],`exactPartial`)},required(...e){return it(Yc,this,e[0])}});function P(e,t){let n={type:`object`,shape:e??{},...g(t)};return new Dc(n)}function F(e,t){return new Dc({type:`object`,shape:e,catchall:Tc(),...g(t)})}let Oc=/*@__PURE__*/ v(`ZodUnion`,(e,t)=>{gi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>us(e,t,n,r),e.options=t.options});function I(e,t){return new Oc({type:`union`,options:e,...g(t)})}let kc=/*@__PURE__*/ v(`ZodDiscriminatedUnion`,(e,t)=>{Oc.init(e,t),vi.init(e,t)});function L(e,t,n){return new kc({type:`union`,options:t,discriminator:e,...g(n)})}let Ac=/*@__PURE__*/ v(`ZodIntersection`,(e,t)=>{yi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r)});function jc(e,t){return new Ac({type:`intersection`,left:e,right:t})}let Mc=/*@__PURE__*/ v(`ZodTuple`,(e,t)=>{Hs(),Si.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(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 zc({type:`optional`,innerType:e}))})}});function Nc(e,t,n){let r=t instanceof x;return new Mc({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}let Pc=/*@__PURE__*/ v(`ZodRecord`,(e,t)=>{Hs(),Ei.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function R(e,t,n){return!t||!t._zod?new Pc({type:`record`,keyType:O(),valueType:e,...g(t)}):new Pc({type:`record`,keyType:e,valueType:t,...g(n)})}let Fc=/*@__PURE__*/ v(`ZodEnum`,(e,t)=>{Di.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(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 Fc({...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 Fc({...t,checks:[],...g(r),entries:i})}});function z(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Fc({type:`enum`,entries:n,...g(t)})}let Ic=/*@__PURE__*/ v(`ZodLiteral`,(e,t)=>{Oi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function B(e,t){return new Ic({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}let Lc=/*@__PURE__*/ v(`ZodTransform`,(e,t)=>{Hs(),ki.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(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 Rc(e){return new Lc({type:`transform`,transform:e})}let zc=/*@__PURE__*/ v(`ZodOptional`,(e,t)=>{ji.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bc(e){return new zc({type:`optional`,innerType:e})}let Vc=/*@__PURE__*/ v(`ZodExactOptional`,(e,t)=>{Mi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`optional`,innerType:e})}let Uc=/*@__PURE__*/ v(`ZodNullable`,(e,t)=>{Ni.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wc(e){return new Uc({type:`nullable`,innerType:e})}let Gc=/*@__PURE__*/ v(`ZodDefault`,(e,t)=>{Pi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Kc(e,t){return new Gc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ve(t)}})}let qc=/*@__PURE__*/ v(`ZodPrefault`,(e,t)=>{Ii.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ss(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Jc(e,t){return new qc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ve(t)}})}let Yc=/*@__PURE__*/ v(`ZodNonOptional`,(e,t)=>{Li.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Xc(e,t){return new Yc({type:`nonoptional`,innerType:e,...g(t)})}let Zc=/*@__PURE__*/ v(`ZodCatch`,(e,t)=>{Bi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Qc(e,t){return new Zc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Dt(t)})}let $c=/*@__PURE__*/ v(`ZodPipe`,(e,t)=>{Vi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ws(e,t,n,r),e.in=t.in,e.out=t.out});function el(e,t){return new $c({type:`pipe`,in:e,out:t})}let tl=/*@__PURE__*/ v(`ZodPreprocess`,(e,t)=>{$c.init(e,t),Ui.init(e,t)}),nl=/*@__PURE__*/ v(`ZodReadonly`,(e,t)=>{Wi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function rl(e){return new nl({type:`readonly`,innerType:e})}let il=/*@__PURE__*/ v(`ZodTemplateLiteral`,(e,t)=>{Ji.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r)});function al(e,t){return new il({type:`template_literal`,parts:e,...g(t)})}let ol=/*@__PURE__*/ v(`ZodCustom`,(e,t)=>{Yi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r)});function sl(e,t){return/* @__PURE__ */ yo(ol,e??(()=>!0),t)}function cl(e,t={}){return/* @__PURE__ */ bo(ol,e,t)}function ll(e,t){return/* @__PURE__ */ xo(e,t)}function ul(e,t){return new tl({type:`pipe`,in:Rc(e),out:t})}let dl={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`};var fl;fl||={};function V(e){return/* @__PURE__ */ Va(Gs,e)}function pl(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`})}}I([O(),A(),M(),xc()]);function ml(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}let hl=Symbol(`json-validation-leave`);function gl(e){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return!0;if(typeof e!=`object`)return!1;let t=/* @__PURE__ */ new Set,n=[e];try{for(;n.length>0;){let e=n.pop();if(e===hl)t.delete(n.pop());else if(!(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))){if(typeof e!=`object`||t.has(e))return!1;if(Array.isArray(e)){t.add(e),n.push(e,hl);for(let t=e.length-1;t>=0;--t)n.push(e[t])}else{if(!ml(e))return!1;t.add(e),n.push(e,hl);for(let t in e)if(Object.hasOwn(e,t)){if(t===`__proto__`)return!1;n.push(e[t])}}}}}catch{return!1}return!0}let H=sl(gl,{message:`Invalid JSON value`}),_l=sl(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&gl(e),{message:`Invalid JSON object`}),vl=F({code:O().min(1),message:O().min(1),retryable:M(),diagnostic:O().min(1).optional(),stage:O().min(1).optional(),durationMs:A().int().nonnegative().optional(),stderrTail:O().min(1).optional()}).superRefine(pl([`diagnostic`,`stage`,`durationMs`,`stderrTail`])),yl=O().max(64).regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/u),bl=e=>O().min(1).max(e).refine(e=>e.trim().length>0),xl=R(yl,P({label:bl(256).optional(),description:bl(1024).optional()}).strict()).refine(e=>Object.keys(e).length<=16,`Too many locales`),Sl=R(yl,bl(4096)).refine(e=>typeof e.en==`string`,`English fallback is required`).refine(e=>Object.keys(e).length<=16,`Too many locales`),Cl=O().refine(e=>e.trim().length>0,{message:`Identifier must not be empty or whitespace`}),U=Cl.brand(),W=Cl.brand(),wl=Cl.brand();Cl.brand();let G=Cl.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).brand();Cl.brand();let Tl=O().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),El=Tl.max(128).regex(/^[A-Za-z0-9._~:-]+$/u,`Permission Mode ID must use transport-safe characters`).brand(),Dl=P({modes:N(P({id:El,label:Tl.max(256),description:Tl.max(1024).optional(),dangerous:M().optional(),localizations:xl.optional()}).strict()).min(1).max(32),defaultModeId:El}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.modes.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Permission Mode IDs must be unique`,path:[`modes`,r,`id`]}),n.add(i.id);n.has(e.defaultModeId)||t.addIssue({code:`custom`,message:`Default Permission Mode must exist in the catalog`,path:[`defaultModeId`]})});P({threadId:W,permissionModeId:El}).strict();let Ol=O().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`});P({sourceThreadId:W,lastTurnId:wl.optional(),targetHarnessId:U,targetModel:Ol.max(1024).optional(),targetThinkingOptionId:Ol.max(128).regex(/^[A-Za-z0-9._~-]+$/u,`Thinking option ID must use transport-safe characters`).optional()}).strict();let kl=P({sourceThreadId:W,sourceHarnessId:U,sourceHarnessLabel:Ol.max(256).optional(),sourceModel:Ol.max(1024).optional(),targetHarnessId:U,targetHarnessLabel:Ol.max(256).optional(),targetModel:Ol.max(1024).optional(),totalTurns:A().int().min(1),boundaryTurnNumber:A().int().min(1),includedTurnNumbers:N(A().int().min(1)),omittedTurns:A().int().min(0),preview:O().max(32e3),createdAtMs:A().int().nonnegative()}).strict();P({threadId:W,handoff:kl}).strict();let Al=O().regex(/^[a-z0-9][a-z0-9-]{0,63}$/u),jl=O().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Role model must not contain control characters`),Ml=z([`stone`,`rose`,`mist`,`sage`,`amber`,`aqua`]),Nl=al([`builtin:`,z([`pm-otter`,`frontend-otter`,`backend-otter`,`reviewer-otter`,`idea-otter`,`researcher-otter`,`writer-otter`,`architect-otter`,`debugger-otter`,`tester-otter`,`classic-otter`,`ops-otter`,`security-otter`,`audio-otter`,`scholar-otter`,`data-otter`,`advisor-otter`,`builder-otter`,`wizard-otter`,`sailor-otter`])]),Pl=/^[a-zA-Z0-9_-]{1,64}\.(png|jpg|jpeg|webp)$/u,Fl=al([`custom:`,O().regex(Pl)]),Il=al([`catalog:`,O().regex(Pl)]),Ll=I([Nl,Fl]),Rl=I([Nl,Il]),zl=I([Ll,Il]),Bl=O().url().max(2048).refine(e=>/^https:\/\//i.test(e),`URL must use https://`),Vl=P({en:O().trim().min(1).max(2e3),"zh-CN":O().trim().min(1).max(2e3)}),Hl=P({slug:Al,name:Vl,description:Vl,avatar:Rl,accentColor:Ml,recommendedHarnessId:U.optional(),author:O().trim().min(1).max(128),authorUrl:Bl.optional(),sourceUrl:Bl.optional(),license:O().trim().min(1).max(64).optional(),official:M().optional(),instructions:O().trim().min(1).max(1e5),updatedAt:V()});P({formatVersion:B(1),generatedAt:V(),roles:N(Hl)});let Ul=P({slug:Al,name:O().refine(e=>e.trim().length>0),avatar:Ll,accentColor:Ml}),Wl=Ul.readonly(),Gl=Ul.extend({description:O(),harnessId:U,model:jl.optional(),thinkingOptionId:G.optional(),instructions:O(),updatedAt:V()});Gl.omit({updatedAt:!0,avatar:!0}).extend({avatar:zl}).partial({slug:!0}),P({locale:O().trim().min(1).max(64).optional()}),P({roles:N(Gl)}),P({slug:Al}),P({role:Gl.nullable()}),P({role:Gl}),P({deleted:M()}),P({refresh:M().optional()}),P({roles:N(Hl),fetchedAt:V(),likes:R(Al,A().int().nonnegative()).optional(),myLikes:R(Al,A().int().min(0).max(5)).optional(),stale:M().optional(),error:O().optional()}),P({slug:Al}),P({slug:Al,likes:A().int().nonnegative(),myLikes:A().int().min(0).max(5),maxLikes:B(5),limitReached:M().optional()});let K=A().int().safe().nonnegative(),Kl=A().finite().nonnegative(),ql=A().finite().min(0).max(100),Jl=P({version:I([B(3),B(4)]).optional(),requestId:O().min(1),turnId:O().min(1).max(1024),outputTokens:K,startedAtMs:K,completedAtMs:K}).strict().refine(e=>e.completedAtMs>e.startedAtMs),Yl=P({version:I([B(2),B(3),B(4)]).optional(),value:Kl,turnId:O().min(1).max(1024),at:K}).strict();P({outputTimings:N(Jl).transform(e=>e.filter(e=>e.version===4)).optional(),outputTokensPerSecond:Yl.refine(e=>e.version===4).optional().catch(void 0),timeToFirstOutputMs:Yl.extend({value:K}).optional()}).strict();let Xl=e=>Sl.refine(t=>Object.values(t).every(t=>t.length<=e)),Zl=P({composerIndicators:N(P({kind:B(`countdown`),id:O().min(1).max(64),expiresAtUnix:K,label:Xl(256).optional(),tooltip:Xl(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:Kl.optional(),sessionOutputTokensPerSecond:Kl.optional(),apiOutputTokensPerSecond:Kl.optional(),reasoningOutputTokens:K.optional(),totalTokens:K.optional(),totalCostUsd:Kl.optional(),totalCredits:Kl.optional(),contextUsagePercent:Kl.optional(),cacheHitRatePercent:ql.optional(),contextWindowTokens:K.optional(),contextUsedTokens:K.optional(),planFiveHourUsedPercent:ql.optional(),planFiveHourResetsAtUnix:K.optional(),planSevenDayUsedPercent:ql.optional(),planSevenDayResetsAtUnix:K.optional(),sessionCacheHitRatePercent:ql.optional(),timeToFirstOutputMs:K.optional(),latestRequestTimeToFirstOutputMs:K.optional(),costSource:z([`publicPrice`,`native`]).optional(),unpricedModels:N(O().min(1)).min(1).optional()}).strict().superRefine((e,t)=>{Object.keys(e).length===0&&t.addIssue({code:`custom`,message:`Thread Usage must contain a reliable field`});let n=e.contextUsedTokens!==void 0;n!==(e.contextWindowTokens!==void 0)&&t.addIssue({code:`custom`,message:`Thread Usage context fields must be provided together`,path:[n?`contextWindowTokens`:`contextUsedTokens`]}),e.contextWindowTokens===0&&t.addIssue({code:`custom`,message:`Thread Usage contextWindowTokens must be greater than zero`,path:[`contextWindowTokens`]}),e.costSource!==void 0&&e.totalCostUsd===void 0&&t.addIssue({code:`custom`,message:`Thread Usage costSource must be provided with totalCostUsd`,path:[`costSource`]}),e.unpricedModels!==void 0&&e.costSource!==`publicPrice`&&t.addIssue({code:`custom`,message:`Thread Usage unpricedModels must be provided with a publicPrice cost`,path:[`unpricedModels`]}),e.planFiveHourResetsAtUnix!==void 0&&e.planFiveHourUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planFiveHourResetsAtUnix must be provided with planFiveHourUsedPercent`,path:[`planFiveHourResetsAtUnix`]}),e.planSevenDayResetsAtUnix!==void 0&&e.planSevenDayUsedPercent===void 0&&t.addIssue({code:`custom`,message:`Thread Usage planSevenDayResetsAtUnix must be provided with planSevenDayUsedPercent`,path:[`planSevenDayResetsAtUnix`]})}),Ql=A().finite().min(0).max(100),$l=z([`weekly`,`monthly`,`five_hour`,`seven_day`,`unknown`]),eu=P({id:O().min(1).max(256),label:O().min(1).max(256),localizations:xl.optional()}).strict(),tu=P({product:O().min(1),periodType:$l.optional(),scope:eu.optional(),localizations:xl.optional(),used:A().finite().nonnegative().optional(),limit:A().finite().nonnegative().optional(),unit:O().min(1).max(32).optional(),usagePercent:Ql,resetsAt:O().min(1).optional()}).strict(),nu=P({availableCount:A().int().safe().positive(),nextExpiresAt:O().min(1).optional(),expiresAt:N(O().min(1)).min(1).max(32).optional()}).strict(),ru=P({used:A().finite().nonnegative().optional(),limit:A().finite().nonnegative().optional(),unit:O().min(1).max(32).optional(),label:O().min(1).optional(),scope:eu.optional(),localizations:xl.optional(),usedPercent:Ql,resetsAt:O().min(1).optional(),periodType:$l,productUsage:N(tu).min(1).optional(),resetCredits:nu.optional()}).strict(),iu=P({amount:A().finite().nonnegative(),currency:O().trim().min(1).max(8),label:O().trim().min(1).max(128).optional()}).strict();P({threadId:W,refresh:B(`exact`).optional()}).strict(),P({threadId:W,usage:Zl.nullable(),accountCredits:ru.optional(),accountBalance:iu.optional(),accountCreditsSupported:M().optional()}).strict();let au=O().refine(e=>e.trim().length>0,{message:`Value must not be empty or whitespace`}),ou=O().min(1).max(512).refine(e=>!/\p{Cc}/u.test(e),`Model Ref must not contain control characters`).brand(),su=z([`priority`,`ultrafast`]),cu=P({id:ou,serviceTier:su.optional()}).strict();function lu(e,t){return e?.id===t?.id&&e?.serviceTier===t?.serviceTier}let uu=au.max(256),du=P({id:G,label:au.max(256)}).strict(),fu=P({ref:cu,label:au.max(256),resolvedModelLabel:uu.optional(),fastModel:cu.optional(),supportedThinkingOptionIds:N(G).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 pu(e,t){if(t)return e?.models.find(e=>lu(e.ref,t)||lu(e.fastModel,t))}let mu=N(du).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)}),hu=z([`catalog`,`activeModel`]),gu=P({models:N(fu),defaultModel:cu.optional(),thinkingOptions:mu,defaultThinkingOptionId:G.optional(),thinkingOptionsScope:hu.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=>lu(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=>lu(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&&!pu(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`]})}),_u=P({fork:M(),forkAcrossCwd:M(),rollbackLastTurn:M()}).strict().refine(e=>e.fork||!e.forkAcrossCwd,{path:[`forkAcrossCwd`],message:`Cross-cwd Fork requires exact history Fork support`}),vu=z([`live`,`atCreate`]),yu=P({configuration:P({selectModel:M(),selectThinkingOption:M(),selectPermissionMode:M(),permissionModeScope:vu.default(`live`)}).strict(),history:_u,subagents:P({observe:M(),readTranscript:M()}).strict().optional(),autonomousTurns:P({observe:M()}).strict().optional(),steer:M().optional(),persistentPlan:M().optional()}).strict();P({effectiveModel:cu.optional(),resolvedModelLabel:uu.optional(),effectiveThinkingOptionId:G.optional(),availableThinkingOptions:mu.optional(),effectivePermissionModeId:El.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 bu=P({open:B(!0)}).strict();I([P({status:B(`ready`),catalog:gu,permissionModes:Dl.optional(),capabilities:yu,webUi:bu.optional()}).strict().superRefine((e,t)=>{let n=e.capabilities.configuration.selectPermissionMode;n!==!!e.permissionModes&&t.addIssue({code:`custom`,message:`Permission Mode catalog and capability must agree`,path:n?[`permissionModes`]:[`capabilities`,`configuration`,`selectPermissionMode`]})}),P({status:z([`notInstalled`,`unavailable`,`error`]),error:vl}).strict()]),P({harnessId:U,cwd:au.max(16384).optional(),refresh:M().optional(),purpose:B(`availability`).optional(),credentialAccess:z([`allow`,`retry`]).optional()}).strict(),P({harnessId:U}).strict(),P({}).strict(),P({threadId:W,model:cu}).strict(),P({threadId:W,thinkingOptionId:G}).strict(),P({threadId:W,includeReferenceCapability:M().optional()}).strict(),L(`owner`,[P({owner:B(`codex`),locked:M(),effectiveModel:cu.optional(),resolvedModelLabel:uu.optional(),effectiveThinkingOptionId:G.optional(),effectivePermissionModeId:El.optional(),history:_u.optional(),supportsThreadReferences:B(!0).optional(),handoff:kl.optional(),roleSnapshot:Wl.optional(),nativeSessionRef:Tc().optional()}),P({owner:B(`external`),harnessId:au.max(256),transportModelId:au.max(8192),effectiveModel:cu.optional(),resolvedModelLabel:uu.optional(),effectiveThinkingOptionId:G.optional(),availableThinkingOptions:mu.optional(),effectivePermissionModeId:El.optional(),catalog:gu.optional(),history:_u,usage:Zl.optional(),handoff:kl.optional(),roleSnapshot:Wl.optional(),nativeSessionRef:Tc().optional(),locked:B(!0)})]),P({threadIds:N(W).min(1).max(100)}).strict().superRefine(({threadIds:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i)&&t.addIssue({code:`custom`,message:`Thread ownership-list IDs must be unique`,path:[`threadIds`,r]}),n.add(i)});let xu=L(`owner`,[P({threadId:W,owner:B(`codex`)}).strict(),P({threadId:W,owner:B(`external`),harnessId:O().max(256).pipe(U)}).strict()]);P({threads:N(xu).min(1).max(100)}).strict().superRefine(({threads:e},t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.entries())n.has(i.threadId)&&t.addIssue({code:`custom`,message:`Thread ownership-list results must be unique`,path:[`threads`,r,`threadId`]}),n.add(i.threadId)}),P({threadId:W,text:O().optional()}).strict(),P({kind:B(`application`),value:O().transform((e,t)=>{try{return JSON.parse(e)}catch{return t.addIssue({code:`custom`,message:`Invalid steering context JSON`}),kt}}).pipe(P({expectedTurnId:wl,clientUserMessageId:O().min(1),delivery:z([`newTurn`,`activeTurn`])}).strict())}).strict().transform(e=>e.value),z([`activeTurn`,`newTurn`]),P({delivery:z([`official`,`activeTurn`,`newTurn`])}).strict();let Su=O().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u),Cu=Su.pipe(U),wu=Cu.refine(e=>e!==`codex`,`The official Codex identity is reserved`),Tu=O().min(1).max(512).refine(e=>!/[\\\u0000:#?]/u.test(e)&&!e.startsWith(`/`)&&!e.split(`/`).some(e=>e===`..`||e===``),`Plugin resources must be relative paths inside the plugin`),Eu=tc().refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Plugin documentation links must be credential-free HTTPS URLs`),Du=P({en:O().max(4096),"zh-CN":O().max(4096).optional()}).strict(),Ou=P({commands:N(P({terminal:O().max(256),command:O().max(4096)}).strict()).max(8),before:Du.optional(),after:Du.optional(),downloads:N(P({label:O().max(128),url:Eu}).strict()).max(8).optional()}).strict(),ku={id:Cu,name:O().trim().min(1).max(128),version:O().min(1).max(128),kind:B(`usage`).optional(),iconStyle:P({vector:P({viewBox:O().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),color:O().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),paths:N(P({d:O().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),fillRule:z([`evenodd`,`nonzero`]).optional(),fill:O().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()}).strict()).min(1).max(32)}).strict().optional(),background:O().regex(/^#[a-f0-9]{6}$/iu).optional(),borderRadius:A().min(0).max(50).optional(),paddingRatio:A().min(0).max(.25).optional()}).strict().optional(),installation:Ou.optional(),notice:Du.optional(),launchCommand:B(!0).optional(),links:P({website:Eu.optional(),documentation:Eu.optional(),installation:Eu.optional()}).strict().optional()};P({manifestVersion:B(1),...ku,adapterApiVersion:A().int().positive(),entry:Tu,icon:Tu.optional()}).strict();let Au=O().max(174828).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u),ju=P({...ku,icon:Au.optional()}).strict();P({}).strict(),P({plugins:N(ju.extend({id:wu})).max(128)}).strict(),P({version:B(1),enabled:N(Cu).max(128)}).strict().refine(e=>new Set(e.enabled).size===e.enabled.length,{message:`Enabled plugin IDs must be unique`,path:[`enabled`]});let Mu=131072,Nu=524288,Pu=Su,Fu=z([`sidebar.thread-layout`,`sidebar.thread-badge`,`appearance.theme`]),Iu=z([`appearance`,`interface`,`workflow`,`analytics`,`integrations`,`tools`]),Lu=O().trim().min(1).max(128);function Ru(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 zu=e=>e.split(`/`).every(e=>!/[. ]$/u.test(e)),Bu=Tu.refine(e=>Ru(e)!==void 0&&zu(e),`Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space`),Vu=O().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu,`Expected an HTTP(S) URL`).pipe(tc({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 Hu(e){return F({en:e,"zh-CN":e})}let Uu=Hu(O().trim().min(1)),Wu=N(Iu).max(Iu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate categories`),Gu=N(Fu).max(Fu.options.length).refine(e=>new Set(e).size===e.length,`Duplicate slots`),Ku={key:O().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),label:Uu,description:Uu.optional()},qu={...Ku,step:A().positive().optional(),default:A().optional()},Ju=F({value:O(),label:Uu}),Yu=L(`type`,[F({...Ku,type:B(`boolean`),default:M().optional()}),F({...Ku,type:B(`string`),placeholder:Uu.optional(),default:O().optional()}),F({...qu,type:B(`number`),min:A().optional(),max:A().optional()}),F({...qu,type:B(`range`),min:A(),max:A()}),F({...Ku,type:B(`select`),options:N(Ju).min(1),default:O().optional()})]).superRefine((e,t)=>{let n=(e,n)=>t.addIssue({code:`custom`,path:[e],message:n});if(e.type===`number`||e.type===`range`){let{min:t=-1/0,max:r=1/0,default:i}=e;t>r&&n(`max`,`Must be at least min`),i!==void 0&&(i<t||i>r)&&n(`default`,`Must be within min and max`)}else if(e.type===`select`){let t=new Set(e.options.map(({value:e})=>e));t.size!==e.options.length&&n(`options`,`Duplicate option values`),e.default!==void 0&&!t.has(e.default)&&n(`default`,`Must match an option value`)}}),Xu=P({manifestVersion:j().positive(),id:Pu,name:I([Lu,Hu(Lu)]),version:O().min(1).max(128),desktopApi:j().positive()}).passthrough().extend({manifestVersion:B(1),desktopApi:B(1),description:F({en:O().max(4096),"zh-CN":O().max(4096).optional()}).optional(),author:O().trim().min(1).max(128).optional(),repository:Vu.optional(),details:F({en:O().max(16384),"zh-CN":O().max(16384).optional()}).optional(),icon:Bu.optional(),screenshots:N(Bu).max(4).refine(e=>new Set(e).size===e.length,`Duplicate screenshots`).optional(),desktop:F({script:Tu,style:Tu.optional()}).optional(),backend:F({script:Tu.refine(zu)}).optional(),slots:Gu.default(()=>[]),settingsSchema:N(Yu).max(32).refine(e=>new Set(e.map(({key:e})=>e)).size===e.length,`Duplicate setting keys`).optional(),categories:Wu.optional()}).strict().refine(e=>e.desktop!==void 0||e.backend!==void 0,`Expected at least one desktop or backend entry`),Zu=O().regex(/^[a-f0-9]{64}$/u),Qu=F({state:z([`running`,`disabled`,`invalid`,`incompatible`,`conflict`,`failed`,`waiting`]),hash:Zu.optional(),error:O().optional(),conflictWith:Pu.optional()});F({controllerPid:j().positive(),targetId:O().nullable(),updatedAt:V(),handledReloadToken:Qs().optional(),extensions:R(O(),Qu),surfaces:R(O(),Qu).optional()});let $u=z([`official`,`community`]);function ed(e){return e.origin===`https://api.github.com`&&/^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(e.pathname)}let td=Vu.refine(e=>{let t=new URL(e);return/\.zip$/iu.test(t.pathname)||ed(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`),nd=F({id:Pu,version:O().trim().min(1).max(128),name:Uu.extend({en:Lu,"zh-CN":Lu}),description:Hu(O().trim().min(1).max(4096)),details:Hu(O().trim().min(1).max(16384)).optional(),author:O().trim().min(1).max(128),repository:Vu,stars:A().int().min(0).optional(),downloads:A().int().min(0).optional(),categories:Wu.optional(),trustTier:$u.default(`community`),icon:Vu.optional(),screenshots:N(Vu).max(4).optional(),downloadUrl:td,sha256:Zu,slots:Gu.optional(),publishedAt:O().optional(),updatedAt:O().optional(),minCodexHostVersion:O().optional()});F({schemaVersion:B(1),generatedAt:O(),extensions:N(nd).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)});let rd=O().trim().min(1).max(128),id=/^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³]) *(?:\.|$)/iu,ad=Pu.refine(e=>!id.test(e),`Reserved extension ID`),od=z([`desktop`,`web`]),sd=Zu,cd=Qs(),ld=Tu.refine(e=>!/[\x00-\x1f\x7f<>"|*]/u.test(e)&&e.split(`/`).every(e=>!/[. ]$/u.test(e)&&!id.test(e)),`Expected a portable relative resource path`).refine(e=>e.split(`/`).length<=32,`Extension resources may be at most 32 segments deep`),ud=Xu.shape,dd=(e,t=0)=>F({en:O().trim().min(t).max(e),"zh-CN":O().trim().min(t).max(e)}),fd=e=>ld.refine(t=>t.endsWith(e),`Expected a ${e} file`),pd=fd(`.mjs`),md=fd(`.css`).optional(),hd=e=>e.normalize(`NFC`).toLowerCase(),gd=F({manifestVersion:B(2),id:ad,name:dd(128,1),version:O().trim().min(1).max(128),description:dd(4096),details:dd(16384).optional(),author:ud.author,repository:ud.repository,icon:ud.icon.refine(e=>e===void 0||ld.safeParse(e).success),screenshots:ud.screenshots.refine(e=>e===void 0||e.every(e=>ld.safeParse(e).success)),categories:ud.categories,settingsSchema:ud.settingsSchema,slots:ud.slots.removeDefault().optional(),page:F({apiVersion:B(1),entry:pd,style:md,title:dd(128,1).optional()}).optional(),widget:F({apiVersion:B(1),entry:pd,style:md}).optional(),desktop:F({apiVersion:B(1),script:fd(`.js`),style:md}).optional(),web:F({apiVersion:B(1),entry:pd.optional(),style:md}).refine(({entry:e,style:t})=>e!==void 0||t!==void 0,`Expected a Web entry or style`).optional(),backend:F({apiVersion:B(1),entry:pd}).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||hd(e)!==hd(r.entry)),{path:[`backend`,`entry`],message:`A backend entry cannot also be a frontend entry`});function _d({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 vd=rd,yd=z([`running`,`waiting`,`idle`,`unknown`]),bd=P({createdAtMs:A().int().nonnegative()}),xd=F({sourceThreadId:W,createdAtMs:A().int().nonnegative()}),Sd=F({harnessId:U,title:O().optional(),status:yd,archived:M(),updatedAtMs:A().int().nonnegative().optional()}),Cd=P({revision:j().nonnegative(),parents:R(W,W),delegations:R(W,bd).optional(),handoffs:R(W,xd).optional(),nodes:R(W,Sd),truncated:M()}).refine(e=>Object.keys(e.nodes).length<=5e3,`Too many Thread tree nodes`).refine(({parents:e,handoffs:t,nodes:n})=>Object.entries(e).every(([e,t])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t))&&Object.entries(t??{}).every(([e,{sourceThreadId:t}])=>Object.hasOwn(n,e)&&Object.hasOwn(n,t)),`Missing Thread tree node`).refine(({parents:e,delegations:t})=>Object.keys(t??{}).every(t=>Object.hasOwn(e,t)),`Delegation metadata requires a matching parent edge`),wd=O().min(1).max(128);F({});let Td=F({subscriptionId:wd});F({}),Td.extend({snapshot:Cd});let Ed=j().nonnegative(),Dd=F({revision:Ed,enabled:N(ad).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});F({version:B(1),seeded:N(ad).max(64).refine(e=>new Set(e).size===e.length,`Duplicate extension IDs`)});let Od=P({version:O().trim().min(1).max(128),publishedAt:O().trim().min(1).max(64).optional(),notes:O().trim().min(1).max(8192),url:Vu.optional()}),{downloadUrl:kd,...Ad}=nd.shape,jd=P({...Ad,id:ad,format:B(`codexhost`),targets:N(od).min(1).max(2).refine(e=>new Set(e).size===e.length,`Duplicate targets`),apis:F({page:j().positive().optional(),widget:j().positive().optional(),desktop:j().positive().optional(),web:j().positive().optional(),backend:j().positive().optional()}),downloadUrl:kd.refine(e=>e.startsWith(`https://`),`Expected HTTPS`),downloads7d:A().int().min(0).optional(),featured:M().optional(),featuredOrder:j().nonnegative().optional(),changelog:N(Od).max(20).optional()}).refine(({targets:e,apis:t})=>{let n=_d({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`);P({schemaVersion:B(2),generatedAt:O().min(1),extensions:N(jd).max(1e4).refine(e=>new Set(e.map(({id:e})=>e)).size===e.length,`Duplicate extension IDs`)}).extend({catalogUrl:Vu,fetchedAt:V(),cached:M(),stale:M().optional()});let Md={id:ad},Nd={...Md,activationId:cd,digest:sd},Pd={...Md,activationId:Nd.activationId.optional()},Fd=O().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`),Id=O().min(1).max(256).refine(e=>e.split(`/`).every(e=>e&&/^[a-z0-9_.-]+$/iu.test(e)&&e!==`.`&&e!==`..`),`Invalid GitHub ref`);function Ld(e){return O().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 Rd=F({type:B(`github`),repository:O().max(150).regex(/^[a-z0-9-]+\/[a-z0-9_-][a-z0-9_.-]*$/iu),ref:Id.optional(),tag:Id.optional(),asset:O().max(255).regex(/^[a-z0-9_.-]+\.zip$/iu).optional(),subpath:ld.optional()}).refine(({ref:e,tag:t,asset:n})=>!e||!t&&!n,`Use either a zipball ref or a release tag/asset`),zd=I([F({type:B(`catalog`),...Md}),Rd,F({type:B(`zip`),base64:Ld(67108864).min(4)}),F({type:B(`zip`),localZipPath:Fd}),F({type:B(`localDir`),localDir:Fd})]),Bd=L(`type`,[F({type:B(`catalog`),...Md}),Rd,F({type:B(`zip`)}),F({type:B(`localDir`)})]),Vd=F({...Nd,manifest:gd,installedAt:V(),source:Bd.optional()}),Hd=e=>O().max(23+4*Math.ceil(e/3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u),Ud={desktopConflictWith:ad.optional()},Wd=z([`none`,`inactive`,`starting`,`running`,`failed`]),Gd=L(`state`,[P({state:B(`updating`),targetVersion:O().trim().min(1).max(128).optional(),startedAt:V()}),P({state:B(`failed`),targetVersion:O().trim().min(1).max(128).optional(),startedAt:V(),updatedAt:V(),error:O().min(1).max(512),interruptedByShutdown:M().optional()})]),Kd=L(`state`,[P({...Vd.shape,state:B(`valid`),enabled:M(),...Ud,iconDataUrl:Hd(Mu).optional(),screenshotDataUrls:N(Hd(Nu)).max(4).optional(),backendState:Wd.optional(),backendError:O().optional(),operation:Gd.optional()}),P({state:z([`invalid`,`incompatible`]),id:O().min(1),enabled:M(),error:O()})]);P({revision:Ed,configuration:Dd,diagnostics:N(O()),extensions:N(Kd)}),F({revision:Ed,extensions:N(Vd.extend({...Ud,settingsRevision:Ed})).max(64)});let q={list:`codexhost/extensions/list`,snapshot:`codexhost/extensions/snapshot`,catalog:`codexhost/extensions/catalog`,catalogIcon:`codexhost/extensions/catalogIcon`,catalogScreenshot:`codexhost/extensions/catalogScreenshot`,install:`codexhost/extensions/install`,update:`codexhost/extensions/update`,enable:`codexhost/extensions/enable`,disable:`codexhost/extensions/disable`,uninstall:`codexhost/extensions/uninstall`,recover:`codexhost/extensions/recover`,asset:`codexhost/extensions/asset`,settingsGet:`codexhost/extensions/settings/get`,settingsSet:`codexhost/extensions/settings/set`,backendInvoke:`codexhost/extensions/backend/invoke`,threadTree:`codexhost/extensions/threadTree`},qd=Object.freeze(Object.values(q));new Set(qd),F({});let Jd={expectedRevision:Ed};F({...Md,...Jd}),P({...Vd.shape,replaced:M()}),L(`state`,[F({state:B(`saved`),configuration:Dd}),F({state:B(`revision-conflict`),revision:Ed})]),F({...Pd,digest:Nd.digest.optional(),path:ld}),F({mimeType:O().min(1),base64:Ld(16777216),digest:Nd.digest}),F({mimeType:z([`image/png`,`image/jpeg`,`image/webp`]),base64:Ld(Mu)});let Yd=j().min(0).max(3);F({mimeType:z([`image/png`,`image/jpeg`,`image/webp`]),base64:Ld(Nu)}),F({settingsRevision:Ed,values:_l}),q.list,P({includeOperations:M().optional()}),q.snapshot,q.catalog,F({forceRefresh:M().optional(),staleWhileRevalidate:M().optional()}),q.catalogIcon,F({...Md}),q.catalogScreenshot,F({...Md,index:Yd}),q.install,F({source:zd}),q.update,F({...Md,expectedDigest:Nd.digest,expectedActivationId:Nd.activationId.optional(),expectedVersion:O().trim().min(1).max(128).optional(),source:zd.optional()}),q.enable,q.disable,q.uninstall,F({...Md,removeData:M().optional(),expectedDigest:Nd.digest.optional()}),F({...Md,removed:M()}),q.recover,F({expectedRevision:Jd.expectedRevision.optional()}),q.asset,q.settingsGet,F(Pd),q.settingsSet,F({...Pd,expectedSettingsRevision:Ed,values:_l}),q.backendInvoke,F({...Pd,method:vd,params:H.optional()}),F({result:H}),q.threadTree;let Xd=4096,Zd;function Qd(e){if(Zd===void 0&&(Zd=typeof TextEncoder==`function`?new TextEncoder:null),Zd!==null)return Zd.encode(e).length;let t=0;for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r<=127)t+=1;else if(r<=2047)t+=2;else if(r>=55296&&r<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=4,n+=1):t+=3}else t+=3}return t}let $d=O().regex(/^remote:[A-Za-z0-9_-]{8,512}$/u),ef=I([$s(),$d]),tf=$s(),nf=O().regex(/^[a-z0-9][a-z0-9_-]{0,47}$/u),rf=z([`none`,`last_speaker`,`all`]),af=z([`active`,`muted`,`removed`]),J=j().nonnegative(),Y=j().positive(),of=J.max(200),X=O().refine(e=>e.trim().length>0),sf=V(),cf={handle:nf.optional(),displayName:X.optional(),note:O().optional()},lf=P({memberId:tf,threadId:W,handle:nf,displayName:X,note:O().optional(),roleSlug:Al.optional(),roleSnapshot:Wl.optional(),harnessId:U,status:af,projectless:M().optional(),showInSidebar:M().optional(),joinedAtSeq:J,lastDeliveredSeq:J,lastRosterVersion:J,lastMemoryVersion:J.default(0),createdAt:sf}),uf=P({workspaceRoot:X,outputDirectory:X}),df=P({hostId:X,displayName:X,state:X.optional(),color:O().optional(),filePreview:M().optional(),memberSidebarVisibility:M().optional(),sharedMemory:M().optional()}),ff=ul(e=>{if(typeof e==`object`&&e&&!Array.isArray(e)){let t=e;if(t.unmentionedPolicy===`member`&&t.unmentionedMemberId!==void 0)return{...t,unmentionedPolicy:`none`}}return e},P({roomId:ef,title:X,defaultCwd:X,projectlessWorkspace:uf.optional(),unmentionedPolicy:rf.default(`none`),unmentionedMemberId:tf.optional(),allowAgentMentions:M().default(!0),maxAgentHops:of.default(10),relayHopLimit:of.optional(),lastSeq:J,lastSpeakerMemberId:tf.optional(),rosterVersion:J,memoryVersion:J.default(0),memorySha256:O().regex(/^[0-9a-f]{64}$/u).optional(),humanEpoch:J,relayPaused:M(),pinned:M(),createdAt:sf,updatedAt:sf,members:N(lf),remote:df.optional()}).superRefine(({members:e,unmentionedPolicy:t,unmentionedMemberId:n},r)=>{n!==void 0&&t!==`none`&&r.addIssue({code:`custom`,path:[`unmentionedMemberId`],message:`A default member can only be set when unmentionedPolicy is "none"`});let i=/* @__PURE__ */ new Set;for(let[t,{handle:n,status:a}]of e.entries())a!==`removed`&&(i.has(n)&&r.addIssue({code:`custom`,path:[`members`,t,`handle`],message:`Handle must be unique among non-removed members`}),i.add(n))})),pf=P({kind:z([`image`,`file`]),attachmentId:X.max(256),name:X.max(256),path:X.max(4096),bytes:J,mediaType:X.max(128).optional(),width:Y.optional(),height:Y.optional()}),mf=P({roomId:ef,seq:Y,messageId:X,senderType:z([`user`,`agent`,`system`]),senderMemberId:tf.optional(),senderHandle:nf.optional(),senderName:O().optional(),senderThreadId:W.optional(),sourceTurnId:X.optional(),replyToSeq:Y.optional(),content:O(),attachments:N(pf).max(12).optional(),mentionedMemberIds:N(tf),mentionAll:M().optional(),hopCount:J,durationMs:J.optional(),createdAt:sf}),hf={...cf,model:jl.optional(),thinkingOptionId:G.optional(),worktree:M().optional()},gf=L(`kind`,[F({kind:B(`role`),roleSlug:Al,...hf}),F({kind:B(`harness`),harnessId:U,...hf}),F({kind:B(`existing`),threadId:W,...cf,includeRecentHistory:M().default(!0).optional()})]),_f={roomId:ef},vf={..._f,memberId:tf},yf={title:X.optional(),unmentionedPolicy:rf.optional(),allowAgentMentions:M().optional(),maxAgentHops:of.optional()};F({}),P({rooms:N(ff)}),F({..._f,limit:Y.optional(),beforeSeq:Y.optional()}),P({room:ff.nullable(),messages:N(mf),hasMore:M()}),F({...yf,defaultCwd:X.optional(),members:N(gf)}),P({room:ff}),F({..._f,...yf,unmentionedMemberId:tf.nullable().optional(),pinned:M().optional(),relayPaused:M().optional()}).superRefine(({unmentionedPolicy:e,unmentionedMemberId:t},n)=>{t!=null&&e!==void 0&&e!==`none`&&n.addIssue({code:`custom`,path:[`unmentionedMemberId`],message:`A default member can only be set when unmentionedPolicy is "none"`})}),F(_f),P({deleted:M()}),F({..._f,member:gf}),P({room:ff,member:lf}),F({...vf,...cf,status:af.optional(),showInSidebar:M().optional()}),F(vf),F({...vf,threadId:W,redeliverFrom:Y.optional(),note:O().optional()}),F({..._f,memberId:tf.optional(),memberHandle:nf.optional(),threadId:W,redeliverFrom:Y.optional(),note:O().optional()}).refine(e=>e.memberId!==void 0!=(e.memberHandle!==void 0),`Provide exactly one of memberId or memberHandle`),P({room:ff,member:lf,previousThreadId:W,awakened:M()});let bf=P({roomId:ef,title:X,memberCount:J,updatedAt:sf,member:P({memberId:tf,threadId:W,handle:nf,displayName:X,status:af,harnessId:U,roleSlug:Al.optional(),roleName:X.optional()}).optional()});F({threadId:W.optional()}),P({rooms:N(bf)}),F({..._f,content:O().max(64e3),attachments:N(pf).max(12).optional(),replyToSeq:Y.optional(),targetMemberIds:N(tf).optional(),mentionAll:M().optional(),notice:M().optional()}).superRefine((e,t)=>{e.notice===!0?(e.content.trim().length===0&&t.addIssue({code:`custom`,path:[`content`],message:`Notice content is required`}),e.content.length>2e3&&t.addIssue({code:`custom`,path:[`content`],message:`Notice content must be at most 2000 characters`}),((e.targetMemberIds?.length??0)>0||e.mentionAll===!0||(e.attachments?.length??0)>0)&&t.addIssue({code:`custom`,path:[`notice`],message:`System notices cannot target members or include attachments`})):e.content.trim().length===0&&(e.attachments?.length??0)===0&&t.addIssue({code:`custom`,path:[`content`],message:`Message content or at least one attachment is required`})}),P({room:ff,message:mf,awakenedMemberIds:N(tf)}),F({..._f,fromSeq:Y.optional(),toSeq:Y.optional(),limit:Y.optional()}),P({..._f,messages:N(mf),totalSeq:J}),F(_f),P({..._f,memoryVersion:J,content:O(),updatedAt:sf}),F({..._f,content:O().refine(e=>Qd(e)<=Xd,`Shared room memory must be at most ${Xd} UTF-8 bytes`),expectedVersion:J.optional()}),P({room:ff,memoryVersion:J,content:O(),updatedAt:sf}),F({cwd:X,roomId:ef.optional()}),P({isGitRepo:M()}),P({threadId:W}).strict(),P({confirmed:M()}).strict();let xf=[`codex-desktop`,`web`,`web-desktop-shell`,`web-mobile`,`ssh-remote`,`cli`],Sf=[`darwin`,`win32`,`linux`],Cf=[`arm64`,`x64`,`ia32`,`arm`],wf=[`zh`,`en`,`ja`,`ko`,`de`,`fr`,`es`,`pt`,`ru`,`other`],Tf=[`codex`,`claude-code`,`antigravity`,`pi`,`opencode`,`cursor-cli`,`deepseek-harness`,`grok`,`omp`,`qwen-code`,`kiro-cli`,`codebuddy`,`workbuddy`,`workbuddy-cn`,`devin`,`hermes`,`qoder`,`qoder-cn`,`kimi-code`,`zcode`,`copilot`,`custom`],Ef=[`official-relay`,`self-hosted-relay`,`tailscale-serve`,`tailscale-funnel`,`tailscale-ip`,`lan`,`custom-proxy`,`remote-peer`],Df=O().min(1).max(40).regex(/^[0-9A-Za-z._+-]+$/u),Of=z(xf),kf=z(wf),Af=z(Tf),jf=z(Ef);new Set(Tf),new Set(wf),P({enabled:M(),forcedOffByEnv:M()}).strict(),P({enabled:M()}).strict(),P({surfaces:N(Of).max(12).optional(),harnesses:N(Af).max(32).optional(),remoteAccess:N(jf).max(12).optional()}).strict(),P({dailyActive:B(!0).optional(),weeklyActive:B(!0).optional(),monthlyActive:B(!0).optional(),newInstall:B(!0).optional(),retainedD1:B(!0).optional(),retainedD7:B(!0).optional(),remoteAny:B(!0).optional(),appVersion:Df.optional(),codexDesktopVersion:Df.optional(),os:z(Sf).optional(),arch:z(Cf).optional(),uiLanguage:kf.optional(),surfaces:N(Of).min(1).max(12).optional(),harnesses:N(Af).min(1).max(32).optional(),remoteAccess:N(jf).min(1).max(12).optional()}).strict().refine(e=>Object.keys(e).length>0,{message:`Telemetry heartbeat must contain at least one countable field`});let Mf=4e3,Nf={threadId:W};L(`action`,[F({...Nf,action:z([`get`,`pause`,`resume`,`clear`])}),F({...Nf,action:z([`create`,`edit`]),objective:O().trim().min(1).refine(e=>Array.from(e).length<=Mf,`A goal objective can have up to ${Mf} characters.`)})]),P({goal:P({threadId:W,objective:O(),status:z([`active`,`paused`,`blocked`,`usageLimited`,`budgetLimited`,`complete`]),tokenBudget:j().positive().nullable().default(null),tokensUsed:j().nonnegative(),timeUsedSeconds:j().nonnegative()}).nullable()});let Pf=z([`codex`,`openai-compatible`,`deepseek-asr`,`openai-chat-audio`]),Ff=z([`native`,`wav`]),If=/(?:^|[_-])(?:key|token|secret|password|passwd|pwd|auth|authorization|credential|signature|sig)(?:$|[_-])|(?:api|access|auth|client|app|private|bearer)[_-]?(?:key|token|secret)/i;function Lf(e){let t=e.trim().toLowerCase().replace(/^\[|\]$/g,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`?!0:/^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(t)}function Rf(e){let t=e.trim();if(!t)return!1;try{let e=new URL(t);if(!e.hostname||e.username!==``||e.password!==``||e.hash!==``)return!1;if(e.protocol!==`https:`){if(e.protocol===`http:`){if(!Lf(e.hostname))return!1}else return!1}for(let t of e.searchParams.keys())if(If.test(t))return!1;return!0}catch{return!1}}let zf=O().max(2048).refine(e=>e===``||Rf(e),{message:`Base URL must be empty or a valid https:// URL (http:// is allowed only for localhost/127.0.0.1/[::1]) without embedded credentials`}),Bf=P({baseUrl:zf,model:O().max(256),hasApiKey:M(),apiKeyHint:O().max(64).optional(),apiKey:Tc().optional()});P({mode:Pf,baseUrl:zf,model:O().max(256),hasApiKey:M(),apiKeyHint:O().max(64).optional(),apiKey:Tc().optional(),audioFormat:Ff.optional(),providers:P({"openai-compatible":Bf,"deepseek-asr":Bf,"openai-chat-audio":Bf}).optional(),codexAvailable:M(),available:M()}),P({mode:Pf,baseUrl:O().max(2048).optional(),model:O().max(256).optional(),apiKey:O().max(4096).nullable().optional()}).strict().superRefine((e,t)=>{let n=e.baseUrl?.trim()??``,r=e.model?.trim()??``;e.mode===`openai-compatible`?Rf(n)||t.addIssue({code:dl.custom,path:[`baseUrl`],message:`OpenAI-compatible mode requires a valid https:// base URL (http:// is allowed only for loopback hosts)`}):e.mode===`openai-chat-audio`?(Rf(n)||t.addIssue({code:dl.custom,path:[`baseUrl`],message:`Multimodal Chat Audio mode requires a valid https:// base URL (http:// is allowed only for loopback hosts)`}),r||t.addIssue({code:dl.custom,path:[`model`],message:`Multimodal Chat Audio mode requires a model name`})):n!==``&&!Rf(n)&&t.addIssue({code:dl.custom,path:[`baseUrl`],message:`Base URL must be empty or a valid https:// URL (http:// is allowed only for loopback hosts)`})});let Vf=O().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);P({available:M(),audioFormat:Ff.optional()}),P({path:O().min(1),mimeType:Vf}).strict();let Hf=z([`credentials-unavailable`,`login-expired`,`rate-limited`,`service-rejected`,`host-incompatible`,`network`,`timeout`,`audio-empty`,`audio-too-large`,`audio-format`,`audio-invalid`]);L(`ok`,[P({ok:B(!0),text:O()}).strict(),P({ok:B(!1),error:P({code:Hf}).strict()}).strict()]),P({}).strict(),P({ghAvailable:M(),starred:M()});let Uf=O().trim().min(1),Wf=O().min(1),Gf=P({icon:O().nullable(),color:O().nullable()}),Kf=Gf.nullable(),qf={create:{method:`codexhost/thread/sections/create`,params:P({name:Uf}).strict()},update:{method:`codexhost/thread/sections/update`,params:P({sectionId:Wf,name:Uf,appearance:Gf.strict().nullable().optional()}).strict()},delete:{method:`codexhost/thread/sections/delete`,params:P({sectionId:Wf}).strict()}};L(`status`,[P({status:B(`unknown`)}),P({status:B(`confirmed`),sectionId:Wf,section:P({id:Wf,name:O().min(1),appearance:Kf}).nullable(),syncPending:M()})]),[qf.create.method,qf.update.method,qf.delete.method,...qd],P({threadSectionsV1:B(!0).optional(),complete:B(!1).optional(),sections:N(P({id:O().min(1),name:O().min(1),appearance:Kf.optional(),threads:N(_l)}))}),P({threadId:O().min(1).max(1024),sectionId:O().min(1).max(1024).nullable(),beforeThreadId:O().min(1).max(1024).nullable().optional(),expectedSourceSectionId:O().min(1).max(1024).optional()}).refine(e=>e.expectedSourceSectionId===void 0||e.sectionId===null),P({threadIds:N(O().min(1))}).strict(),P({threadId:O().min(1).max(1024),pinned:M()}).strict(),P({}).strict(),P({parents:R(O().min(1),O().min(1))}).strict(),P({prompt:O().max(16384).optional()}).strict(),P({projects:N(P({id:O(),name:O(),rootPaths:N(O()),createdAt:A().int().optional()})),nativeProjects:B(!0).optional(),assignments:R(O(),O()),projectless:N(O()),pinned:N(O()),sectionProjects:R(O(),N(O())).optional(),pinnedProjects:N(O()).optional()});let Jf=R(O(),Cc()),Yf=P({epoch:O().uuid(),sequence:A().int().nonnegative()});L(`type`,[P({type:B(`projects-changed`),cursor:Yf}),P({type:B(`skills-changed`),cursor:Yf,cwd:O().optional()}),P({type:B(`harness-inspection-changed`),cursor:Yf,harnessId:O().min(1)}),P({type:B(`display-settings-changed`),cursor:Yf}),P({type:B(`sections-changed`),cursor:Yf}),P({type:B(`groups-changed`),cursor:Yf,roomId:O().optional()}),P({type:B(`preferences-changed`),cursor:Yf,revision:A().int().nonnegative()}),P({type:B(`extensions-changed`),cursor:Yf,revision:Ed}),P({type:B(`hello`),version:B(1),cursor:Yf,reset:M()}),P({type:B(`changed`),cursor:Yf,threadId:O().min(1),method:O().min(1)})]);let Xf=L(`type`,[P({type:B(`text`),id:O(),prompt:O(),secret:M().optional(),optional:M().optional()}),P({type:B(`choice`),id:O(),prompt:O(),multiple:M(),allowOther:M(),optional:M().optional(),options:N(P({value:O(),label:O(),description:O().optional()}))})]),Zf=L(`type`,[P({type:B(`approval`),title:O(),description:O().optional(),subject:Cc().optional(),actions:N(P({id:O(),label:O(),effect:O()}))}),P({type:B(`question`),title:O().optional(),questions:N(Xf)})]),Qf=P({requestId:I([O(),A().int()]),threadId:O(),kind:z([`approval`,`question`]),interaction:Zf,request:Jf}),$f=P({id:O().min(1),clientUserMessageId:O().min(1),input:N(Jf),presentationInput:N(Jf).nullable().optional()}).passthrough();P({fields:N(P({path:N(I([O(),A().int().nonnegative()])),originalLength:A().int().nonnegative()}))});let ep=P({id:O().min(1),status:O().min(1),codexhostTurnOutcome:P({status:B(`unknown`),reason:O()}).optional(),items:N(P({id:O().min(1),type:O().min(1)}).passthrough()),codexhostFileOperations:N(P({beforeItemId:O().nullable(),item:P({id:O().min(1),type:O().min(1)}).passthrough()})).optional(),error:P({message:O().optional()}).passthrough().nullable().optional(),fingerprint:O().min(1).optional(),unchanged:B(!0).optional()}).passthrough(),tp=P({id:O().min(1).max(512),fingerprint:O().min(1).max(128)});P({threadId:O().min(1),knownTurns:N(tp).max(64).optional(),truncateToolOutput:M().optional()});let np=P({harnessId:O().min(1),nativeSessionId:O().min(1)});P({cursor:Yf,activeTurnId:O().min(1).nullable().optional(),command:P({name:O().min(1),turn:ep,subsequentTurnId:O().min(1).optional()}).optional(),thread:P({id:O().min(1),cwd:O(),modelProvider:O().min(1),createdAt:A(),updatedAt:A(),recencyAt:A().nullable().optional(),status:P({type:O()}).passthrough(),name:O().nullable().optional(),preview:O().optional(),roleSnapshot:Wl.optional(),codexhostImportSource:np.optional(),turns:N(ep).length(0)}).passthrough(),turnsPage:P({data:N(ep).max(5),nextCursor:O().nullable()}),configuration:P({codexCollaborationMode:z([`plan`,`default`]).optional(),native:P({model:O().min(1).max(1024).optional(),reasoningEffort:O().min(1).max(128).optional()}).optional(),effectiveModel:cu.optional(),effectiveThinkingOptionId:G.optional(),effectivePermissionModeId:El.optional()}),queue:P({items:N($f),pausedReason:z([`interrupted`,`outcome-unknown`,`failed`]).nullable()}).optional(),interactions:N(Qf),handoff:kl.optional()}),P({version:B(1),owner:B(`service`).optional(),pid:A().int().positive(),port:A().int().min(1).max(65535),token:O().regex(/^[0-9a-f]{64}$/u),startedAt:A(),epoch:O().uuid(),capabilities:P({peerDelegation:B(1).optional(),threadReferenceContext:B(1).optional()}).optional()}),P({epoch:O().uuid(),threadId:O().min(1),requestId:I([O(),A().int()]),result:Jf}),P({includeArchived:M().optional(),officialCursor:P({live:O().nullable(),archived:O().nullable().optional()}).strict().optional(),scope:I([P({cwd:O().min(1).max(4096),excludeCwds:N(O().min(1).max(4096)).max(1024)}).strict(),P({projectId:O().min(1).max(1024),legacyThreadIds:N(O().min(1).max(1024)).max(1024),rootPaths:N(O().min(1).max(4096)).max(1024).optional()}).strict()]).optional()}).strict(),P({threads:N(_l),ownership:N(xu),archivedThreadIds:N(W),officialCursor:P({live:O().nullable(),archived:O().nullable().optional()}).strict().optional()}).strict(),ju.pick({id:!0,name:!0,icon:!0,iconStyle:!0});let rp=F({threadId:O().max(1024),title:O().max(240),project:O().max(240),harness:F({id:O().min(1).max(128),name:O().min(1).max(128)}).optional(),state:z([`idle`,`running`,`waiting`,`completed`,`failed`]),updatedAt:A().nonnegative()});F({epoch:O().max(128),revision:j().nonnegative(),running:j().nonnegative(),waiting:j().nonnegative(),sessions:N(rp).max(32).default([]),notifications:N(F({threadId:O().max(1024),key:O().max(4096),kind:z([`completed`,`failed`,`approval`,`question`]),revision:j().nonnegative()})).max(256)}),Object.freeze({appearance:[`appearance`,`外观主题`],interface:[`interface`,`界面增强`],workflow:[`workflow`,`效率与协作`],analytics:[`analytics`,`数据与统计`],integrations:[`integrations`,`外部集成`],tools:[`tools`,`实用工具`]}),P({threadId:W.optional(),cwd:O().min(1).optional()}).strict().refine(e=>!(e.threadId&&e.cwd),{message:`Specify threadId or cwd, not both`});let ip=P({name:O().min(1).regex(/^[^\s[\]]+$/u),description:O().optional(),path:O().min(1),scope:z([`project`,`global`]),source:O().min(1)}).strict();P({revision:A().int().nonnegative(),complete:M(),skills:N(ip),warnings:N(O()).optional()}).strict(),P({cwd:O().min(1).optional()}).strict();let ap=P({kind:z([`public`,`relay`,`tailscale-funnel`,`tailscale-https`,`tailscale`,`lan`,`virtual`]),url:O().min(1)}).strict(),op=L(`status`,[P({status:B(`not-installed`)}),P({status:B(`not-running`)}),P({status:B(`not-logged-in`)}),P({status:B(`https-disabled`)}),P({status:B(`not-serving`),command:O()}),P({status:B(`occupied`),target:O()}),P({status:B(`serving`),url:O(),funnel:M()}),P({status:B(`error`),message:O()})]);P({state:op,error:O().optional()}).strict();let sp=L(`status`,[P({status:B(`on`)}),P({status:B(`off`)}),P({status:B(`invalid`),reason:O()})]),cp=P({lan:M(),autostart:sp}).strict(),lp=P({expiresAt:O().optional(),issuing:M(),failure:P({detail:O().optional(),retryAt:O(),paused:M()}).optional()}),up=L(`status`,[P({status:B(`off`),reason:z([`invite`,`name-taken`,`banned`]).optional()}),P({status:B(`connecting`),reason:z([`full`,`unreachable`]).optional()}),P({status:B(`connected`),url:O(),certificate:lp}),P({status:B(`missing-certificate`),url:O(),certificate:lp}),P({status:B(`stopped`),reason:z([`replaced`,`rejected`,`unsupported-version`])})]);O().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i).transform(e=>e.toLowerCase()),O().regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)?$/);let dp=z([`official`,`self-hosted`]);P({secret:O().min(1),lastUsedAt:A().nullable(),networkUrls:N(ap),directCandidates:N(ap).optional(),tailscale:op,background:cp.optional(),relay:P({state:up,enabled:M(),kind:dp,officialHost:O(),customHost:O().optional(),officialHostname:O().optional(),customHostname:O().optional(),quotaUntil:O().optional()}).strict().optional()}).strict();let fp=F({threadId:O().min(1).max(1024),view:z([`result`,`messages`]),from:A().int().min(1).max(2**53-1).optional(),to:A().int().min(1).max(2**53-1).optional()}),pp=/^[a-zA-Z0-9_-]{1,64}$/u,Z=O().regex(pp),mp=O().regex(pp),hp=O().regex(/^remote-peer:[a-zA-Z0-9_-]{1,64}$/u),gp=z([`relay`,`tailscale`,`lan`,`ssh`,`custom`]),_p=z([`auto`,`key`,`password`]);P({host:O().trim().min(1).max(255),port:A().int().min(1).max(65535).optional(),user:O().trim().min(1).max(128).optional(),identityFile:O().trim().min(1).max(1024).optional(),authMode:_p.default(`auto`),remoteDataDir:O().trim().min(1).max(1024).optional()});let vp=P({host:O().min(1).max(255),port:A().int().min(1).max(65535).optional(),user:O().min(1).max(128).optional(),authMode:_p,keyInstalled:M().optional()}),yp=[`blue`,`purple`,`cyan`,`green`,`amber`,`rose`,`slate`],bp=z(yp);new Set(yp);let xp=z([`connected`,`connecting`,`auth-error`,`offline`,`disabled`]),Sp=P({peerId:Z,hostId:hp,nodeId:mp.optional(),name:O().min(1).max(120),color:bp.optional(),origin:O().min(1).max(2048),transportKind:gp,ssh:vp.optional(),encrypted:M(),enabled:M(),state:xp,supportsPeerPairing:M().optional(),pairedBack:M().optional(),linkedPeerIds:N(Z).max(128).optional(),latencyMs:A().int().nonnegative().optional(),version:O().max(128).optional(),platform:O().max(64).optional(),hostname:O().max(255).optional(),homeDir:O().max(4096).optional(),lastError:O().max(1e3).optional(),projectCount:A().int().nonnegative(),createdAt:O(),updatedAt:O()});P({localPlatform:O().max(64).optional(),peers:N(Sp)}),P({connectionUrl:O().min(1).max(4096).optional(),origin:O().min(1).max(2048).optional(),token:O().min(1).max(2048).optional(),name:O().trim().min(1).max(120).optional(),color:bp.optional(),pairBack:M().optional(),meshPeerIds:N(Z).max(64).optional(),selfOrigin:O().min(1).max(2048).optional()}).refine(e=>!!e.connectionUrl||!!e.origin&&!!e.token,`Provide either connectionUrl or both origin and token`),F({origin:O().min(1).max(2048),token:O().min(1).max(2048),name:O().trim().min(1).max(120).optional(),color:bp.optional(),expectedNodeId:mp.optional()}),P({status:z([`added`,`updated`,`existing`]),peerId:Z,hostId:hp,nodeId:mp.optional()});let Cp=z([`added`,`updated`,`existing`,`failed`,`skipped`]);P({results:N(P({targetPeerId:Z,targetName:O().min(1).max(120),introducedHost:I([B(`local`),Z]),introducedName:O().min(1).max(120),status:Cp,error:O().max(1e3).optional()}))}),P({peerIds:N(Z).max(64).optional(),includeSelf:M().optional(),includeMesh:M().optional(),selfOrigin:O().min(1).max(2048).optional()}),P({peerId:Z,name:O().trim().min(1).max(120).optional(),color:bp.nullable().optional(),connectionUrl:O().min(1).max(4096).optional(),origin:O().min(1).max(2048).optional(),token:O().min(1).max(2048).optional(),enabled:M().optional()}),P({peerId:Z}),P({removed:M()}),P({peerId:Z.optional(),connectionUrl:O().min(1).max(4096).optional(),origin:O().min(1).max(2048).optional(),token:O().min(1).max(2048).optional()}).refine(e=>!!e.peerId||!!e.connectionUrl||!!e.origin&&!!e.token,`Provide peerId, connectionUrl, or both origin and token`);let wp=P({id:O().min(1).max(1024),name:O().min(1).max(512),path:O().min(1).max(8192)});P({ok:M(),nodeId:mp.optional(),supportsPeerPairing:M().optional(),pairedBack:M().optional(),latencyMs:A().int().nonnegative().optional(),origin:O().max(2048).optional(),transportKind:gp.optional(),encrypted:M().optional(),version:O().max(128).optional(),platform:O().max(64).optional(),hostname:O().max(255).optional(),homeDir:O().max(4096).optional(),projectCount:A().int().nonnegative().optional(),projects:N(wp).optional(),error:O().max(1e3).optional()});let Tp=P({id:O().min(1).max(1024),name:O().min(1).max(512),path:O().min(1).max(8192),threadIds:N(O().min(1).max(1024))}),Ep=P({attachments:B(1).optional(),workspaceFiles:B(1).optional(),officePreview:B(1).optional(),delegation:B(1).optional(),peerPairing:B(1).optional(),extensionUpdateTracking:B(1).optional(),groupMemberSidebarVisibility:B(1).optional(),groupSharedMemory:B(1).optional()}),Dp=P({version:O().max(128),platform:O().max(64),hostname:O().max(255),homeDir:O().max(4096).optional(),epoch:O().min(1).max(256),nodeId:mp.optional(),peerNodes:R(hp,mp).refine(e=>Object.keys(e).length<=128).optional(),projects:N(Tp),capabilities:Ep.optional()});F({threadId:O().min(1).max(1024),scope:O().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:O().min(1).max(256).optional(),mode:z([`queue`,`steer`]).optional(),expectedTurnId:O().min(1).max(1024).nullable().optional(),content:N(L(`type`,[F({type:B(`text`),text:O()}),F({type:B(`file`),receiptId:O().min(1).max(128)})])).min(1).max(64)});let Op=P({ok:B(!1),error:P({code:O(),message:O(),details:R(O(),Cc()).optional()})});I([P({ok:B(!0),value:P({receiptId:O().min(1),file:P({attachmentId:O(),name:O(),bytes:A().int().nonnegative()})})}),Op]),I([P({ok:B(!0),value:P({accepted:B(!0)})}),Op]);let kp=P({name:O().min(1).max(512),path:O().min(1).max(8192),kind:B(`directory`)});P({peerId:Z,path:O().min(1).max(8192).optional()}),P({path:O().min(1).max(8192),parentPath:O().min(1).max(8192).nullable(),homeDir:O().min(1).max(8192).optional(),entries:N(kp)}),P({peerId:Z,parentPath:O().min(1).max(8192),name:O().min(1).max(255).refine(e=>e.trim().length>0,`Directory name cannot be blank`)}),P({path:O().min(1).max(8192),name:O().min(1).max(255)}),P({peerId:Z,path:O().min(1).max(8192),title:O().trim().min(1).max(255).optional()}),P({peerId:Z,workspaceId:O().min(1).max(1024),title:O().trim().min(1).max(255)}),P({peerId:Z,workspaceId:O().min(1).max(1024)}),P({workspaceId:O().min(1).max(1024).optional(),manifest:Dp}),P({sessionHostId:O().min(1).max(128).optional()}),P({hosts:N(P({hostId:I([B(`local`),hp]),name:O().min(1).max(120),isLocal:M().optional(),color:bp.optional(),hostname:O().max(255).optional()}))}),P({hostId:I([B(`local`),hp])}),P({harnesses:N(P({id:O().regex(/^[a-z0-9][a-z0-9-]*$/u),name:O().min(1).max(120)}))}),P({hosts:N(P({alias:O().min(1).max(255),hostName:O().max(255).optional(),user:O().max(128).optional(),port:A().int().min(1).max(65535).optional(),identityFile:O().max(1024).optional()}))}),P({host:O().trim().min(1).max(255),port:A().int().min(1).max(65535).optional(),user:O().trim().min(1).max(128).optional(),identityFile:O().trim().min(1).max(1024).optional(),authMode:_p.default(`auto`),password:O().max(1024).optional(),installAuthorizedKey:M().optional(),name:O().trim().min(1).max(120).optional(),color:bp.optional(),remoteDataDir:O().trim().min(1).max(1024).optional(),sessionId:O().min(1).max(128).optional()}),P({ok:M(),codexhostInstalled:M(),version:O().max(128).optional(),nodeId:mp.optional(),platform:O().max(64).optional(),hostname:O().max(255).optional(),latencyMs:A().int().nonnegative().optional(),errorCode:O().max(128).optional(),error:O().max(1e3).optional()}),P({ok:M(),version:O().max(128).optional(),message:O().max(1e3).optional()}),P({promptId:O().min(1).max(128),sessionId:O().min(1).max(128).optional(),peerId:Z.optional(),host:O().min(1).max(255),kind:z([`host-key`,`password`,`passphrase`,`otp`,`generic`]),prompt:O().min(1).max(1e3),echo:M()}),P({promptId:O().min(1).max(128),sessionId:O().min(1).max(128).optional(),response:O().max(1024).optional(),cancel:M().optional()}),F({hostId:hp,threadId:O().min(1).max(1024).optional()});let Ap=z([`listHarnesses`,`inspect`,`start`,`send`,`cancel`,`read`,`answer`,`list`]);F({operation:Ap,hopCount:A().int().min(0).max(16),sourceId:Z.optional(),input:_l});let jp=F({code:O().min(1).max(128),message:O().max(4096),details:_l.optional()});I([F({ok:B(!0),value:H}),F({ok:B(!1),error:jp})]);let Mp=F({id:O().min(1).max(1024),name:O().min(1).max(512),path:O().min(1).max(8192)});F({hosts:N(F({hostId:hp,nodeId:mp.optional(),displayName:O().min(1).max(120),online:M(),state:xp,delegation:M(),projects:N(Mp),platform:O().max(64).optional(),hostname:O().max(255).optional(),homeDir:O().max(4096).optional()}))}),F({version:B(1),instanceId:O().min(1).max(128),pid:A().int().positive(),endpoint:O().min(1).max(256),token:O().regex(/^[0-9a-f]{64}$/u),startedAt:A().int().nonnegative()}),I([F({operation:B(`hosts`)}),F({operation:Ap,hostId:hp,hopCount:A().int().min(0).max(16),timeoutMs:A().int().min(1).max(12e4).optional(),input:_l})]);let Np=P({id:O().min(1).max(256),harnessId:O().min(1),label:O().min(1).max(512),provider:z([`openai-codex`,`xai`])}).strict(),Pp=O().regex(/^[a-z][a-z0-9-]{0,47}$/),Fp=P({name:Pp,source:Np,importedAt:O()}).strict(),Ip=L(`action`,[P({action:B(`list`)}).strict(),P({action:B(`import`),sourceId:O().min(1).max(256),name:Pp,confirmed:B(!0)}).strict(),P({action:B(`reimport`),sourceId:O().min(1).max(256),name:Pp,confirmed:B(!0)}).strict(),P({action:B(`remove`),name:Pp,confirmed:B(!0)}).strict()]),Lp=P({provider:O().min(1).max(128),type:z([`oauth`,`api_key`,`unknown`]),label:O().min(1).max(512).optional(),vendor:z([`openai-codex`,`xai`]).optional()}).strict();P({sources:N(Np),targets:N(P({harnessId:O(),providers:N(z([`openai-codex`,`xai`])),imports:N(Fp),others:N(Lp).default([])}).strict())}).strict(),P({targetHarnessId:O().min(1).max(128).optional(),request:Ip}).strict(),P({events:M()});let Rp=N(F({agent:O().min(1).max(128),section:z([`main`,`more`,`auto`])})).max(256).refine(e=>new Set(e.map(e=>e.agent)).size===e.length,`Duplicate Harness IDs`);F({entries:Rp.nullable()}),F({}),F({entries:Rp,initializeOnly:M().optional()});let zp=F({enabled:M(),timeoutMinutes:A().int().min(5).max(1440)});Object.freeze({enabled:!0,timeoutMinutes:10});let Bp=O().regex(/^external$/u),Vp=U.transform(e=>String(e)),Hp=F({model:cu.optional(),thinkingOptionId:G.optional(),permissionModeId:El.optional()}).refine(e=>!!(e.model||e.thinkingOptionId||e.permissionModeId),`A default configuration must contain a preference`);L(`mode`,[F({mode:B(`global`)}),F({mode:B(`last`)}),F({mode:B(`manual`),harnessId:U})]);let Up=F({lastHarness:U.optional(),byHarness:R(Vp,Hp)}),Wp=F({model:cu.optional(),thinkingOptionId:G.optional()}).refine(e=>!!(e.model||e.thinkingOptionId),`A delegation default must contain a Model or Thinking option`),Gp=F({byHarness:R(Vp,Wp)}),Kp=O().min(1).max(1024),qp=P({idleRelease:zp.optional(),favorites:R(Vp,N(Kp).max(2048)).default({}),newThread:Up.optional(),delegation:Gp.optional(),showGroupChatsInSidebar:M().optional()});F({scope:Bp,revision:A().int().nonnegative(),values:qp}),F({scope:Bp.default(`external`)});let Jp=L(`kind`,[F({kind:B(`idleRelease`),value:zp}),F({kind:B(`favorite`),harnessId:U,modelId:Kp,enabled:M()}),F({kind:B(`favorites`),harnessId:U,modelIds:N(Kp).max(2048)}),F({kind:B(`newThread`),lastHarness:U.optional(),harnessId:U.optional(),configuration:Hp.optional()}),F({kind:B(`delegation`),harnessId:U,configuration:Wp.nullable()}),F({kind:B(`groupChatsSidebar`),visible:M()})]);F({scope:Bp.default(`external`),operations:N(Jp).min(1).max(256),initializeOnly:M().optional(),expectedRevision:A().int().nonnegative().optional()}).superRefine((e,t)=>{for(let n of e.operations)n.kind===`newThread`&&(!n.lastHarness&&!n.configuration||!!n.harnessId!=!!n.configuration)&&t.addIssue({code:`custom`,message:`A default Harness or complete configuration is required`})}),F({version:B(1),revision:A().int().nonnegative(),scopes:R(Bp,qp)});let Yp=A().finite().nonnegative(),Xp=F({input:Yp,output:Yp,cacheRead:Yp.optional(),cacheWrite:Yp.optional(),cacheWrite1h:Yp.optional()}),Zp=O().max(512).refine(e=>e.trim()===e&&e.length>0,`Model ID is required`);F({path:O(),entries:N(F({key:O(),price:Xp})),error:O().nullable()}),F({}),F({key:Zp,price:Xp.nullable(),previousKey:Zp.optional()}),F({model:Zp});let Qp=F({official:M().optional(),canonicalModelId:O().min(1).optional(),provider:O().min(1).max(512),model:O().min(1).max(512),price:Xp});F({price:Xp.nullable(),suggestions:N(Qp).max(6).optional()});let $p=[`today`,`7d`,`30d`,`90d`,`all`],Q=A().int().min(0).max(2**53-1),em=O().regex(/^\d{4}-\d{2}-\d{2}$/u),tm=O().min(1).max(128),nm=O().min(1).max(512),rm=O().min(1).max(4096);F({range:z($p),timeZone:O().min(1).max(128).refine(e=>{try{return new Intl.DateTimeFormat(`en`,{timeZone:e}),!0}catch{return!1}},`Unsupported usage statistics timezone`).optional(),harness:tm.optional(),model:nm.nullable().optional(),project:rm.nullable().optional(),date:em.optional()});let im=F({requests:Q,inputTokens:Q,cachedInputTokens:Q,cacheWriteInputTokens:Q,cacheKnownInputTokens:Q,cacheHitCachedInputTokens:Q,cacheHitInputTokens:Q,outputTokens:Q,reasoningOutputTokens:Q,costUsd:A().finite().min(0),unpricedRequests:Q,unmeteredRequests:Q}),am=im.shape,om=F({harness:tm,sessionId:O().min(1).max(512),project:rm.nullable(),title:O().min(1).max(200).optional(),models:N(nm).max(16),firstAtMs:Q,lastAtMs:Q,...am});F({range:z($p),from:em.nullable(),to:em,filters:F({harness:tm.nullable(),model:nm.nullable(),unknownModel:M(),project:rm.nullable(),unknownProject:M(),date:em.nullable()}),reading:F({complete:M(),sources:Q,read:Q}),failures:N(F({harness:tm,message:O().max(2048)})).max(256),options:F({harnesses:N(tm).max(256),models:N(nm.nullable()).max(4096),projects:N(rm.nullable()).max(4096)}),modelLabels:N(F({harness:tm,model:nm,label:nm})).max(4096).optional(),credits:N(F({harness:tm,model:nm.nullable(),credits:A().finite().min(0),reportedRequests:Q,requests:Q})).max(4096).optional(),totals:im,daily:N(F({date:em,harness:tm,...am})).max(2e5),hourly:N(F({weekday:A().int().min(0).max(6),hour:A().int().min(0).max(23),...am})).max(168),byHarness:N(F({harness:tm,...am})).max(256),byModel:N(F({model:nm.nullable(),...am,harnessPricedRequests:Q})).max(4096),byProject:N(F({project:rm.nullable(),...am})).max(4096),sessions:N(om).max(100),recentSessions:N(om).max(100).optional()}),P({threadId:W}),P({discarded:M()});let sm=L(`type`,[P({id:O().min(1),type:B(`choice`),prompt:O(),options:N(P({value:O().min(1),label:O(),description:O().optional()})).min(1),multiple:M(),allowOther:M(),optional:M()}),P({id:O().min(1),type:B(`text`),prompt:O(),multiline:M(),secret:B(!1),optional:M(),placeholder:O().optional(),prefill:O().optional()})]),cm=P({interactionId:O().min(1),turnId:O().min(1),title:O().optional(),questions:N(sm).min(1)}).refine(({questions:e})=>e.some(e=>e.type===`choice`&&e.multiple),{message:`Shared cards require at least one multi-select question`});F({threadId:O().min(1)}),P({questions:N(cm)}),F({threadId:O().min(1),turnId:O().min(1),interactionId:O().min(1),answers:R(O(),N(O())),cancelled:M().default(!1)}),P({accepted:B(!0)});let lm=`codexhostActiveTurnId`,um=/* @__PURE__ */ new Set([lm,`codexhostTurnChanges`,`codexhostToolOutput`,`codexGoal`]),dm=P({path:O(),oldText:O().nullable(),newText:O()});P({sessionId:O().min(1),turn:A().int().nonnegative(),path:O().min(1).optional()}),P({diffs:N(dm)}),F({}),F({}),P({reference:P({sessionId:O().min(1),epoch:O().min(1),turn:A().int().nonnegative(),seq:A().int().nonnegative(),callId:O().min(1),part:A().int().nonnegative(),version:O().min(1)}),length:A().int().nonnegative(),bytes:A().int().nonnegative()}),F({}),F({}),F({title:O().trim().min(1).max(200),type:z([`info`,`warning`,`danger`]),body:O().trim().min(1).max(16384)}),F({}),F({url:O().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)}),Object.freeze(/* @__PURE__ */ `codexhost/console/remote-connections.codexhost/runtime/status.codexhost/remote/ssh-setup.codexhost/harness/plugins/list.codexhost/harness/display-settings/capabilities.codexhost/harness/display-settings/get.codexhost/harness/display-settings/set.codexhost/harness/inspect.codexhost/harness/installation.codexhost/harness/installation/start.codexhost/harness/installation/status.codexhost/harness/launch-settings/get.codexhost/harness/launch-settings/set.codexhost/harness/web-ui/open.codexhost/harness/accounts/sources.codexhost/harness/accounts/list.codexhost/harness/accounts/inspect.codexhost/harness/credential-imports.codexhost/harness/session-import/sources.codexhost/harness/session-import/list.codexhost/harness/session-import/import.codexhost/account/list.codexhost/account/refresh.codexhost/account/usage/inspect.codexhost/usage/model-prices/get.codexhost/usage/model-prices/set.codexhost/usage/model-prices/default.codexhost/usage/statistics/get.codexhost/update/check.codexhost/update/start.codexhost/update/status.codexhost/update/macos-signing/status.codexhost/update/macos-signing/setup.codexhost/update/macos-signing/remove`.split(`.`));let fm=z([`idle`,`running`,`busy`,`closing`,`failed`,`blocked`]),pm=z([`none`,`disabled`,`timeout`,`operation`,`background`,`identity`,`persistence`,`closeFailed`]);F({threadId:O(),title:O(),harnessId:O(),state:fm,reason:pm,inactiveMs:A().nonnegative()}),F({threadId:W,turnId:wl});let mm=P({email:O().trim().min(1).max(320).optional(),label:O().trim().min(1).max(256).optional(),plan:O().trim().min(1).max(128).optional(),credits:ru.optional(),balance:iu.optional()}).strict();function hm(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 gm=hm(mm),_m={harnessId:U,harnessName:O().trim().min(1).max(128)},vm=P(_m).strict();P({}).strict(),P({sources:N(vm).max(128)}).strict(),P({harnessId:U,refresh:M().optional()}).strict(),P({..._m,account:gm.nullable(),accounts:N(gm).max(8).optional()}).strict(),P({refresh:M().optional()}).strict(),P({accounts:N(hm(mm.extend(_m))).max(128)}).strict(),P({harnessId:wu,model:cu.optional(),thinkingOptionId:G.optional(),permissionModeId:El.optional(),prewarm:B(!0).optional()}).strict();let ym=O().trim().min(1).max(4096).refine(e=>!/[\u0000\r\n]/u.test(e),`Invalid entrypoint path`);P({harnessId:wu}).strict().extend({path:ym.nullable()}),P({path:ym.nullable(),restartRequired:M()}).strict(),P({harnessId:U,action:z([`check`,`update`,`install`]),confirmedVersion:O().min(1).max(128).optional()}).strict().refine(({action:e,confirmedVersion:t})=>e===`update`||t===void 0);let bm=P({currentVersion:O().min(1).max(128),latestVersion:O().min(1).max(128),updateAvailable:M(),canUpdate:M(),latestVerifiedVersion:O().min(1).max(128).optional(),confirmationRequired:B(!0).optional(),versionKind:z([`cli`,`application`]).optional(),manualUpdateUrl:tc().max(2048).refine(e=>/^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(e),`Manual updates require a credential-free HTTPS URL`).optional(),message:O().max(2048).optional(),messageCode:O().min(1).max(128).optional(),notice:Sl.optional(),latestVersionKind:z([`unknown`,`tracking-branch`]).optional()}).strict();P({taskId:O().uuid()}).strict(),L(`status`,[P({taskId:O().uuid(),status:B(`running`)}).strict(),P({taskId:O().uuid(),status:B(`succeeded`),result:bm}).strict(),P({taskId:O().uuid(),status:B(`failed`),error:P({code:A().int(),message:O().min(1).max(2048)}).strict()}).strict()]);let xm=O().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u),Sm=O().trim().min(1),Cm=z([`free`,`go`,`plus`,`pro`,`prolite`,`team`,`self_serve_business_prolite`,`self_serve_business_usage_based`,`business`,`ent26`,`enterprise_cbp_automation`,`enterprise_cbp_usage_based`,`enterprise`,`edu`,`edu_plus`,`edu_pro`,`unknown`]),wm=P({accountId:xm,label:Sm.max(256),email:O().email().max(320).optional(),planType:Cm.optional()}).strict(),Tm=z([`ready`,`unavailable`]);P({version:B(2),currentAccountId:xm.nullable(),phase:Tm,revision:A().int().nonnegative(),instanceId:Sm.max(1024).optional(),accounts:N(wm).max(1)}).strict(),P({accountId:xm,refresh:M().optional()}).strict(),P({accountId:xm,usage:Zl.nullable(),accountCredits:ru.optional(),freshness:z([`live`,`cached`]),observedAt:O().datetime().nullable()}).strict();let Em=1e3,Dm=O().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),Om=Dm.max(1024),km=P({nativeSessionId:Om,title:Dm.max(4096).nullable(),updatedAt:A().int().nonnegative().max(864e13),cwd:Dm.max(16384),running:M().nullable()}).strict();P({}).strict(),P({harnesses:N(P({harnessId:wu,name:Dm.max(128)}).strict()).max(128)}).strict(),P({harnessId:wu,query:O().trim().max(4096).refine(e=>!e.includes(`\0`)).optional(),offset:A().int().nonnegative().safe().optional(),limit:A().int().min(1).max(Em).optional()}).strict(),P({candidates:N(km).max(Em),total:A().int().nonnegative().safe()}).strict(),P({harnessId:wu,nativeSessionId:Om}).strict(),P({threadId:Dm.max(1024).pipe(W)}).strict();let Am=O().refine(e=>e.trim().length>0,`Value must not be empty or whitespace`).refine(e=>!e.includes(`\0`),`Value must not contain NUL`),jm=Om,Mm=km;P({}).strict(),P({candidates:N(Mm).max(1e3)}).strict(),P({nativeSessionId:jm}).strict(),P({threadId:Am.max(1024).pipe(W)}).strict(),P({threadId:W,lastTurnId:wl}).strict(),P({threadId:W}).strict();let Nm=O().trim().min(1).max(128).regex(/^[A-Za-z0-9._:-]+$/u).brand();P({commands:N(P({id:Nm,invocation:O().min(1).max(128),label:O().trim().min(1).max(128),description:O().trim().min(1).max(512).optional(),localizations:xl.optional(),argumentMode:z([`none`,`text`]),kind:z([`command`,`skill`]).optional()}).strict()),warnings:N(O().min(1)).optional(),source:z([`live`,`static`]).optional()}).strict().superRefine((e,t)=>{let n=/* @__PURE__ */ new Set;for(let[r,i]of e.commands.entries())n.has(i.id)&&t.addIssue({code:`custom`,message:`Harness command IDs must be unique`,path:[`commands`,r,`id`]}),n.add(i.id)}),P({harnessId:U,cwd:O().min(1).optional()}).strict(),P({threadId:W}).strict(),P({threadId:W,commandId:Nm,turnId:wl.optional(),arguments:_l.optional()}).strict(),P({accepted:B(!0),turnId:wl.optional()}).strict();let Pm=B(`2.0`).optional(),Fm=Tc().optional(),Im=O().min(1),Lm=I([O(),A().int()]),Rm=P({code:A().int(),message:O(),data:H.optional()}).catchall(H).superRefine(pl([`data`]));I([P({jsonrpc:Pm,id:Lm,method:Im,params:H.optional(),result:Fm,error:Fm}).catchall(H).superRefine(pl([`jsonrpc`,`params`,`result`,`error`])),P({jsonrpc:Pm,id:Fm,method:Im,params:H.optional(),result:Fm,error:Fm}).catchall(H).superRefine(pl([`jsonrpc`,`id`,`params`,`result`,`error`])),P({jsonrpc:Pm,id:Lm,method:Fm,params:Fm,result:H,error:Fm}).catchall(H).superRefine(pl([`jsonrpc`,`method`,`params`,`error`])),P({jsonrpc:Pm,id:Lm,method:Fm,params:Fm,result:Fm,error:Rm}).catchall(H).superRefine(pl([`jsonrpc`,`method`,`params`,`result`]))]);let zm=O().refine(e=>e.trim().length>0,{message:`Native identifier must not be empty or whitespace`});F({harnessId:U,nativeSessionId:zm,locator:H.optional(),formatVersion:B(1)}).superRefine(pl([`locator`])),F({harnessId:U,nativeSessionId:zm,nativeTurnKey:zm,formatVersion:B(1)}),F({harnessId:U,nativeSessionId:zm,checkpointId:zm,locator:H.optional(),formatVersion:B(1)}).superRefine(pl([`locator`]));let Bm=O().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u),Vm=z([`npm`,`windows-installer`,`macos-dmg`,`linux-archive`]),Hm=z([`prepared`,`downloading`,`waiting-for-exit`,`installing`,`restarting`,`succeeded`,`failed`]),Um=F({completed:A().int().nonnegative(),total:A().int().positive()}).refine(e=>e.completed<=e.total,{path:[`completed`],message:`completed must not exceed total`}),Wm=F({version:Bm,installation:Vm,phase:Hm,updatedAt:A().int().nonnegative(),downloadedBytes:A().int().nonnegative().optional(),totalBytes:A().int().positive().optional(),npmDownload:Um.optional(),error:O().min(1).max(500).nullable(),serviceStopOutput:O().optional()}).superRefine((e,t)=>{e.downloadedBytes!==void 0&&e.totalBytes!==void 0&&e.downloadedBytes>e.totalBytes&&t.addIssue({code:`custom`,path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`})});F({});let Gm=O().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u,`release notes URL must identify a codexhost GitHub Release`),Km=z([`idle`,`downloading`,`ready`,`failed`]),qm=F({downloadedBytes:A().int().nonnegative(),totalBytes:A().int().positive()}).refine(e=>e.downloadedBytes<=e.totalBytes,{path:[`downloadedBytes`],message:`downloadedBytes must not exceed totalBytes`});P({currentVersion:Bm,installation:Vm.nullable(),latestVersion:Bm.nullable(),updateAvailable:M(),installationAvailable:M(),releaseNotes:O().min(1).max(2e4).nullable(),releaseNotesUrl:Gm.nullable(),status:Wm.nullable(),error:O().min(1).max(500).nullable(),stagedVersion:Bm.nullable().optional(),backgroundPhase:Km.optional(),backgroundDownload:qm.nullable().optional(),backgroundError:O().min(1).max(500).nullable().optional(),runningTaskCount:A().int().nonnegative().optional()}),F({status:Wm}),F({status:Wm.nullable()}),F({supported:M(),enabled:M(),certificatePresent:M(),appSignedWithLocalCert:M(),appPath:O().min(1).nullable(),certificateName:O().min(1),certificateSha1:O().regex(/^[0-9A-Fa-f]{40}$/u).nullable()});let Jm=F({icon:O().min(1).max(16).optional(),title:O().min(1).max(120),body:O().min(1).max(1200),contributors:N(O().min(1).max(39)).max(30)}),Ym=F({summary:O().min(1).max(600).optional(),themes:N(Jm).min(1).max(12)}),Xm=F({version:Bm,publishedAt:V(),url:O().max(300).regex(/^https:\/\/github\.com\/BytePioneer-AI\/codex-host\/releases\/tag\/v[0-9A-Za-z.+-]+$/u),zh:Ym.nullable(),en:Ym.nullable()}).refine(e=>e.zh!==null||e.en!==null,{message:`an announcement needs at least one language`});F({manual:M().optional()}),F({announcement:Xm.nullable(),unread:M()}),F({version:Bm}),RegExp(String.raw`^- \[([^\]\n]+)\]\(thread://([^\s()<>"?#/]+)(?:\?hostId=([^\s()<>"?#/&]+))?\): `+`(${[`completed`,`failed`,`interrupted`,`needsInput`,`timedOut`,`unreadable`,`notFound`].join(`|`)})(?:\. (.+))?$`,`u`);let Zm=z([`idle`,`installing`,`restarting`,`succeeded`,`failed`]);P({runningVersion:O().nullable(),installedVersion:O().nullable(),restartRequired:M(),remote:M(),updateSupported:M(),update:P({phase:Zm,targetVersion:O().nullable(),error:O().nullable()})});let Qm=P({version:O().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u)}).strict();P({hostname:O().min(1).max(1024).refine(e=>!e.startsWith(`-`)&&!/\s/u.test(e)),port:A().int().min(1).max(65535).nullable(),identity:O().max(4096).nullable(),action:z([`inspect`,`install`,`update`,`restart`,`repair`,`uninstall`]),uninstallPackage:M().optional(),version:O().regex(/^\d+\.\d+\.\d+$/u).nullable()}).strict(),P({state:z([`installed`,`not-installed`])}).strict();let $=O().min(1).max(1024),$m={hostId:$.regex(/^(?:remote-(?:ssh(?:-|:)|control:)|remote-peer:[a-zA-Z0-9_-]{1,64}$)/u)},eh={...$m,threadId:$},th=O().min(1).max(8e3),nh={text:th,requestId:$},rh=N($).min(2).max(100).refine(e=>new Set(e).size===e.length,`Queued submission IDs must be distinct`);L(`accepted`,[P({accepted:B(!0),startQueuedItemId:$.optional()}),P({accepted:B(!1),code:z([`remote/queue-unavailable`,`remote/steer-unavailable`,`remote/turn-changed`,`remote/send-rejected`,`session/queue-item-not-found`,`session/queue-item-starting`]),message:O()})]),L(`available`,[P({available:B(!1)}),P({available:B(!0),canReorder:B(!0).optional(),items:N(P({id:$,clientUserMessageId:$,preview:O().max(801)})).max(100)})]);let ih=L(`kind`,[F({kind:B(`hosts`)}),F({kind:B(`create`),...$m,cwd:O().min(1).max(8192),epoch:$}),F({kind:B(`projectHarnesses`),...$m,epoch:$}),F({kind:B(`inspectHarness`),...$m,epoch:$,cwd:O().min(1).max(8192),harnessId:$}),F({kind:B(`startSelected`),...$m,epoch:$,cwd:O().min(1).max(8192),harnessId:$,model:O().min(1).max(4096),serviceTier:z([`priority`,`ultrafast`]).optional(),reasoningEffort:$.optional()}),F({kind:B(`status`),...eh}),F({kind:B(`list`),...$m,cursor:O().nullable(),archived:M(),includeLoaded:B(!0).optional()}),F({kind:B(`read`),...eh,page:F({cursor:O().min(1).max(8192).nullable(),epoch:$.optional(),sortDirection:z([`asc`,`desc`]).optional(),limit:A().int().min(1).max(20).optional()}).refine(e=>e.cursor===null||e.epoch!==void 0,{message:`A history continuation requires its connection epoch`}).optional()}),F({kind:B(`usage`),...eh,epoch:$}),F({kind:B(`configure`),...eh,epoch:$,modelId:$.optional(),serviceTier:su.optional(),thinkingOptionId:$.optional(),permissionModeId:$.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`}),F({kind:B(`prompt`),...eh,epoch:$,text:th,requestId:$.optional()}),F({kind:B(`queue`),...eh,epoch:$}),F({kind:B(`delivery`),...eh,epoch:$,action:L(`kind`,[F({kind:B(`enqueue`),...nh}),F({kind:B(`steer`),...nh,turnId:$}),F({kind:B(`remove`),itemId:$}),F({kind:B(`reorder`),itemIds:rh}),F({kind:B(`start`),itemId:$,onlyIfHead:B(!0).optional()}),F({kind:B(`sendNow`),itemId:$})])}),F({kind:B(`interrupt`),...eh,epoch:$,turnId:$}),F({kind:B(`rename`),...eh,epoch:$,name:O().min(1).max(512)}),F({kind:B(`archive`),...eh,epoch:$,archived:M()}),F({kind:B(`respond`),...eh,epoch:$,requestId:I([$,A().int()]),result:R(O(),Cc())})]),ah=O().min(1).max(1024),oh=P({hostId:ah,displayName:O().min(1).max(1024),source:z([`codex-managed`,`discovered`]),sshAlias:O().max(1024).nullable(),sshHost:O().min(1).max(1024),sshPort:A().int().min(1).max(65535).nullable(),identity:O().max(4096).nullable(),autoConnect:M(),connectionAnalyticsId:O().max(1024).optional()}),sh=F({displayName:O().min(1).max(1024),hostname:O().min(1).max(1024),sshPort:A().int().min(1).max(65535).nullable(),identity:O().max(4096).nullable()});L(`action`,[F({action:B(`session`),operation:ih}),F({action:B(`list`)}),F({action:B(`catalog`)}),F({action:B(`read-thread`),hostId:ah.refine(e=>e!==`local`),input:fp}),F({action:B(`save`),draft:sh,previous:oh.nullable()}),F({action:B(`remove`),previous:oh}),F({action:B(`connect`),hostId:ah,enabled:M()}),F({action:B(`state`),hostId:ah}),F({action:B(`runtime`),hostId:ah}),F({action:B(`update`),hostId:ah.refine(e=>e!==`local`),version:Qm.shape.version})]),I([F({result:H}),F({error:F({code:A().int(),message:O()})})]),F({prompt:O().trim().min(1).max(2e3),cwd:O().max(4096).nullable()}),O().trim().min(1).max(60).nullable();let ch=O().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u),lh=I([O(),P({en:O()}).catchall(O())]),uh=P({title:lh.optional(),description:lh.optional(),icon:O().max(349592).regex(/^data:image\/(?:svg\+xml|png|jpeg|webp);base64,[A-Za-z0-9+/]*={0,2}$/u).optional(),error:O().optional()});P({extensions:N(P({id:ch,name:O().min(1).max(214),version:O().min(1).max(128),format:B(`dsh`),supportedTargets:Nc([B(`web`)]),enabledTargets:N(B(`web`)).max(1),source:O().min(1).max(4096),projectUrl:O().max(4096).url({protocol:/^https?$/u}).optional(),installedAt:O(),meta:uh.optional(),loadError:O().optional()})),loadedIds:N(ch),safeMode:M(),storeError:O().optional()});let dh=O().trim().max(2048).url({protocol:/^https?$/u,normalize:!0}).refine(e=>!/[\s\\?#]/u.test(e)&&!e.split(`/`)[2]?.includes(`@`),`Use an HTTP(S) registry URL without credentials, a query, or a fragment.`).transform(e=>e.endsWith(`/`)?e:`${e}/`);P({spec:O().trim().min(1).max(4096),registry:dh.optional()}).strict(),P({id:ch,enabled:M()}).strict(),P({id:ch}).strict(),B(1);function fh(e,t,n){let r=/* @__PURE__ */ new Map;for(let e of t)r.set(n(e),e);let i=e.map(e=>r.get(n(e))).filter(e=>e!==void 0),a=new Set(i.map(n));for(let e=0;e<t.length;e++){let r=t[e];
|
|
114
114
|
/* v8 ignore next -- dense-array guard: index is bounded by baseline.length. */
|
|
115
|
-
if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let
|
|
116
|
-
`,r:`\r`,t:` `},
|
|
117
|
-
`||e===`\r`||e===` `}function
|
|
115
|
+
if(r===void 0||a.has(n(r)))continue;let o=i.length;for(let r=e+1;r<t.length;r++){let e=t[r];if(e===void 0||!a.has(n(e)))continue;let s=i.findIndex(t=>n(t)===n(e));if(s!==-1){o=s;break}}i.splice(o,0,r),a.add(n(r))}return i}let ph={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
|
|
116
|
+
`,r:`\r`,t:` `},mh=/[\\\u0000-\u001f]/u;function hh(e){return e===` `||e===`
|
|
117
|
+
`||e===`\r`||e===` `}function gh(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(mh),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++)gh(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=ph[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&&mh.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(hh(e))return;if(e===`{`){this.#r=`key-or-end`;return}this.fail();return;case`key-or-end`:if(hh(e))return;if(e===`}`){this.#r=`closed`;return}if(e===`"`){this.beginKey(t);return}this.fail();return;case`key-only`:if(hh(e))return;if(e===`"`){this.beginKey(t);return}this.fail();return;case`key`:this.stepKey(e,t);return;case`colon`:if(hh(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(hh(e))return;if(e===`,`){this.#r=`key-only`;return}if(e===`}`){this.#r=`closed`;return}this.fail();return;case`closed`:if(hh(e))return;this.fail();return;
|
|
118
118
|
/* v8 ignore next 2 -- scan() stops stepping once the view is invalid. */
|
|
119
119
|
case`invalid`:return;
|
|
120
120
|
/* v8 ignore next 2 -- Every scanner mode has a handler above. */
|
|
121
|
-
default:
|
|
121
|
+
default:_h(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){hh(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===`}`||hh(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 _h(e,t){let n=JSON.stringify(e)??String(e);throw Error(`unreachable variant${t?` in ${t}`:``}: ${n}`)}function vh(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 yh(e){return Object.getPrototypeOf(e)===null&&vh(e,`Object`)}function bh(e){let t=Object.getPrototypeOf(e);if(!Array.isArray(t)||!vh(t,`Array`))return!1;let n=Object.getPrototypeOf(t);return typeof n==`object`&&!!n&&yh(n)}function xh(e){let t=Object.getPrototypeOf(e);return t===null||typeof t==`object`&&yh(t)}function Sh(e){let t=Reflect.ownKeys(e);if(!t.some(t=>typeof t!=`string`||!Object.prototype.propertyIsEnumerable.call(e,t)))return t}function Ch(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(!bh(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(!xh(r))return;let o=Sh(r);if(o===void 0)return;let s=t?{}:void 0;s!==void 0&&i(e.destination,s),n.add(r),a.push({kind:`leave`,source:r});for(let e=o.length-1;e>=0;e--){let t=o[e];
|
|
122
122
|
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
123
|
-
if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function
|
|
123
|
+
if(t===void 0)return;a.push({kind:`object-property`,source:r,key:t,...s===void 0?{}:{target:s}})}}return!t||r}function wh(e){return Ch(e,!0)}function Th(e){let t=/* @__PURE__ */ new WeakSet,n=[{kind:`visit`,node:e}];for(;n.length>0;){let e=n.pop();
|
|
124
124
|
/* v8 ignore next -- the loop condition guarantees one pending task. */
|
|
125
125
|
if(e===void 0)continue;if(e.kind===`property`){n.push({kind:`visit`,node:e.source[e.key]});continue}let r=e.node;if(typeof r!=`object`||!r||r instanceof AbortSignal||t.has(r))continue;t.add(r),Object.freeze(r);let i=Object.keys(r);for(let e=i.length-1;e>=0;e--){let t=i[e];
|
|
126
126
|
/* v8 ignore next -- the loop is bounded by the captured key count. */
|
|
127
|
-
t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function _h(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 vh=class{rebuild;listeners=/* @__PURE__ */ new Set;dirty=!1;notifyPending=!1;scheduled=`none`;scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!==`microtask`&&this.schedule(`microtask`)}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled===`none`&&this.schedule(typeof globalThis.requestAnimationFrame==`function`?`frame`:`microtask`)}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}};function yh(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!yh(e[n],t[n]))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.getPrototypeOf(t)||n!==Object.prototype&&n!==null)return!1;let r=e,i=t,a=Object.keys(r),o=Object.keys(i);if(a.length!==o.length)return!1;for(let e of a)if(!Object.hasOwn(i,e)||!yh(r[e],i[e]))return!1;return!0}var bh=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new vh(()=>{});constructor(e){this.anyIgnoredKeys=e}get revision(){return this.writeRevision}faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<=r.seq?!1:r!==void 0&&yh(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyLive(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<r.seq?!1:r!==void 0&&yh(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyCached(e){for(let t of Object.keys(e)){let n=this.rows.get(t);n?.kind!==`sequenced`&&(n!==void 0&&yh(n.value,e[t])?this.writeRevision+=1:(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t)))}}seed(e,t,n){let r=e.values;for(let[e,t]of this.rows)t.kind!==`cached`||Object.hasOwn(r,e)||(this.rows.delete(e),this.changed(e));for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.writeRevision+=1,this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyIgnoredKeys?.has(e)||this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new vh(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}};let xh=/* @__PURE__ */ new WeakMap;function Sh(e){return e.length*2}function Ch(e,t){return Sh(e)+Sh(t)+64}function wh(e){if(e===void 0||e.size===0)return 0;let t=64;for(let[n,r]of e)t+=Ch(n,r);return t}function Th(e,t=0,n){if(e==null)return 0;switch(typeof e){case`string`:return Sh(e);case`number`:case`boolean`:case`bigint`:case`symbol`:return 8;case`function`:return 64;case`object`:{if(t>=12)return 64;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength+64;let r=xh.get(e);if(r!==void 0)return r;if(n?.has(e))return 8;let i=n??/* @__PURE__ */ new Set;i.add(e);let a=64;try{if(Array.isArray(e)){a+=e.length*8;for(let n=0;n<e.length;n+=1)a+=Th(e[n],t+1,i)}else if(e instanceof Map)for(let[n,r]of e)a+=64+Th(n,t+1,i)+Th(r,t+1,i);else if(e instanceof Set)for(let n of e)a+=8+Th(n,t+1,i);else{let n=e;for(let e in n)Object.hasOwn(n,e)&&(a+=Sh(e)+8+Th(n[e],t+1,i))}}finally{i.delete(e)}return t===0&&n===void 0&&Object.isFrozen(e)&&xh.set(e,a),a}default:return 0}}function Eh(e){let t=xh.get(e);if(t!==void 0)return t;let n=Th(e);return xh.set(e,n),n}function Dh(e){let t=0;for(let n=0;n<e.length;n+=1)t+=8+Eh(e[n]);return t}function Oh(e){return e===void 0?0:64+Sh(e.epoch)+Dh(e.records)}function kh(e){let t=64,n;if(e.journal!==void 0){t+=64+Sh(e.journal.epoch),n=/* @__PURE__ */ new Set;for(let r of e.journal.records)t+=8+Eh(r),n.add(r),typeof r.event==`object`&&r.event!==null&&n.add(r.event)}t+=64;for(let r of e.entries){if(t+=8,n!==void 0){if(n.has(r))continue;if(typeof r.event==`object`&&r.event!==null&&n.has(r.event)){t+=64;continue}}t+=Eh(r)}return t+=wh(e.toolOutputs),t+=Th(e.projections),t}var Ah=class{readRemote;values=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;maxBytes;totalBytes=0;constructor(e,t,n={}){if(this.readRemote=e,this.maxBytes=Math.max(0,n.maxBytes??8388608),t!==void 0)for(let[e,n]of t)this.remember(e,n)}get estimatedBytes(){return this.totalBytes}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return this.values.delete(t),this.values.set(t,n),Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.remember(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}remember(e,t){let n=this.values.get(e);n!==void 0&&(this.totalBytes-=Ch(e,n),this.values.delete(e));let r=Ch(e,t);if(!(r>this.maxBytes))for(this.values.set(e,t),this.totalBytes+=r;this.totalBytes>this.maxBytes&&this.values.size>0;){let t=this.values.entries().next().value;if(t[0]===e)break;this.values.delete(t[0]),this.totalBytes-=Ch(t[0],t[1])}}};function jh(){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 Mh(e){return{kind:`leaf`,entries:e,length:e.length}}function Nh(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Ph(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 Fh(e,t,n,r){let i;return{get entries(){return i??=Ph(e),i},hasMore:t,revision:n,change:r}}var Ih=class{listeners=/* @__PURE__ */ new Set;window=Mh([]);estimatedEntryBytes=0;snapshot=Fh(this.window,!1,0,{kind:`replace`,entries:[]});get estimatedBytes(){return this.estimatedEntryBytes}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=Mh(e),this.estimatedEntryBytes=Dh(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Nh(Mh(e),this.window),this.estimatedEntryBytes+=Dh(e),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Nh(this.window,Mh(t)),this.estimatedEntryBytes+=8+Eh(e),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Ph(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=Mh(n),this.estimatedEntryBytes=Dh(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Fh(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Lh(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function Rh(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function zh(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 Bh(e){let t=hh(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Vh(e){let t=[];for(let n of e){let e=Hh(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 Hh(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`:{Gh(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=Wh(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Uh(t,e.length,t.type),t}case`tool-call-chunks`:{Gh(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=Wh(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 Uh(t,e.length,t.type),t}case`chunk`:{Gh(t,[`type`,`time`,`chunk`],`chunk`);let e=Rh(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=Bh(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return gh({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Uh(e,t,n){if(Rh(e.time0),zh(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 Wh(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function Gh(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 Kh=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;estimatedPendingBytes(){if(this.pending.size===0)return 0;let e=0;for(let t of this.pending.values())e+=8+Eh(t);return e}replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Vh(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=qh(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 qh(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function Jh(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let Yh={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},Xh={...Yh,turnWindow:{...Yh.turnWindow,minMessages:200}};var Zh=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 Kh;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionTarget;submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Ih;cachedProjectionBytesRevision=-1;cachedProjectionBytes=0;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new Ah(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new bh,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 vh(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){if(this.submissionTarget!==void 0)return this.submissionTarget.beginSubmission(e);let t=jh(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onObserved:e.onObserved,onRetire:e.onRetire,observed:!1,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}handoffSubmissions(e){if(e=e.submissionOwner(),e===this||this.submissionTarget!==void 0)return[];let t=this.pendingSubmissions.map(e=>e.requestId);if(t.length===0)return t;e.pendingSubmissions=[...e.pendingSubmissions,...this.pendingSubmissions];for(let n of t){let t=this.submissionSettlements.get(n);t!==void 0&&e.submissionSettlements.set(n,t);let r=this.inFlightPrompts.get(n);r!==void 0&&e.inFlightPrompts.set(n,r)}this.submissionSettlements.clear(),this.submissionTarget=e,e.promptAttempted||=this.promptAttempted;for(let{event:t}of e.eventSource.getSnapshot().entries)e.observeSubmissionEvent(t);return e.observeSubmissionInbox(),e.notifier.markDirty(),t}submissionOwner(){return this.submissionTarget?.submissionOwner()??this}get hasInFlightPrompts(){return this.inFlightPrompts.size>0}activeTurnForSteering(){let e=this.projections.get(em);return typeof e==`string`?e:null}async prompt(e,t,n,r){if(this.submissionTarget!==void 0)return this.submissionTarget.prompt(e,t,n,r);let i=r??jh();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=Lh(),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:Lh()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}let c=this.submissionOwner();return!s.ok&&s.error.code===`remote/outcome-unknown`&&c.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(c.acceptPrompt(),s):(r!==void 0&&c.retireFailedSubmission(r),c.promptError={op:`send`,error:s.error,requestId:i},c.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i);let e=this.submissionOwner();e.inFlightPrompts.get(i)===a&&e.inFlightPrompts.delete(i),this.notifier.markDirty()}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...Yh})}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,...Xh}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}estimatedBytes(){let e=this.projections.revision;return this.cachedProjectionBytesRevision!==e&&(this.cachedProjectionBytes=Th(this.projections.values()),this.cachedProjectionBytesRevision=e),(this.eventSource.estimatedBytes>0?this.eventSource.estimatedBytes:Oh(this.cachedJournal))+this.assistantStream.estimatedPendingBytes()+this.toolOutputs.estimatedBytes+this.cachedProjectionBytes}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:new Map(this.toolOutputs.values),entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(tm),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(Yh),e!==this.openGeneration||this.events!==n)return;this.cachedJournal=void 0,this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:Jh(e.page.projections),e.page.assistantStream);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq)),e.key===`subagent`&&this.address?.mode===`unknown`&&this.notifier.markDirty()}let t=this.lastSyncedAt;this.lastSyncedAt=Date.now(),(e.type!==`assistant-stream`||t===void 0)&&this.notifier.markFrameDirty()}installWindow(e,t,n,r){let i=this.assistantStream.replace(e,r);if(this.baseSeq=m(e[0]?.event.seq??0),this.hasMore=t,this.pendingHistory!==null&&(this.pendingHistory.beforeSeq=this.baseSeq,this.pendingHistory.hasMore=t,this.pendingHistory.pages.length=0),i.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,tm),this.eventSource.replace(i,t),n!==void 0)for(let[e,{receipt:t}]of this.submissionSettlements)t!==void 0&&t.seq<=n.asOfSeq&&this.scheduleObservedRetirement(e,t.attachments);for(let e of i)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event);else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId);else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),t&&this.notifier.markDirty()}else e?.type===`transient`&&this.eventSource.append(e.entry)}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e);return}let n=this.hasMore;this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t),n!==t&&this.notifier.markDirty();for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:$h(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=$h(e.content),this.notifySubmissionObserved(i,i.admitted),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,$h(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}notifySubmissionObserved(e,t){e.observed||(e.observed=!0,e.onObserved?.(t))}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,this.notifySubmissionObserved(n,t),Qh(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){if(this.submissionTarget!==void 0){this.submissionTarget.retireFailedSubmission(e);return}let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){if(this.submissionTarget!==void 0){this.submissionTarget.finishSubmission(e,t);return}let n=this.submissionSettlements.get(e);
|
|
127
|
+
t!==void 0&&n.push({kind:`property`,source:r,key:t})}}return e}function Eh(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),i.push({...e,depth:t});let r=n.get(e.sessionId);if(r!==void 0)for(let e of r)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 Dh=class{rebuild;listeners=/* @__PURE__ */ new Set;dirty=!1;notifyPending=!1;scheduled=`none`;scheduleGeneration=0;constructor(e){this.rebuild=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}markDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled!==`microtask`&&this.schedule(`microtask`)}markFrameDirty(){this.dirty=!0,this.notifyPending=!0,this.scheduled===`none`&&this.schedule(typeof globalThis.requestAnimationFrame==`function`?`frame`:`microtask`)}notifyNow(){this.dirty=!0,this.notifyPending=!0,this.invalidateSchedule(),this.flush()}ensureFresh(){this.dirty&&(this.dirty=!1,this.rebuild())}schedule(e){let t=++this.scheduleGeneration;this.scheduled=e;let n=()=>{t===this.scheduleGeneration&&(this.scheduled=`none`,this.flush())};e===`frame`?globalThis.requestAnimationFrame(n):queueMicrotask(n)}invalidateSchedule(){this.scheduleGeneration++,this.scheduled=`none`}flush(){this.notifyPending&&this.listeners.size!==0&&(this.notifyPending=!1,this.dirty&&(this.dirty=!1,this.rebuild()),(0,a.notifySubscribers)(this.listeners,`[session-controller]`))}};function Oh(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null)return!1;if(Array.isArray(e)||Array.isArray(t)){if(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Oh(e[n],t[n]))return!1;return!0}let n=Object.getPrototypeOf(e);if(n!==Object.getPrototypeOf(t)||n!==Object.prototype&&n!==null)return!1;let r=e,i=t,a=Object.keys(r),o=Object.keys(i);if(a.length!==o.length)return!1;for(let e of a)if(!Object.hasOwn(i,e)||!Oh(r[e],i[e]))return!1;return!0}var kh=class{anyIgnoredKeys;rows=/* @__PURE__ */ new Map;channels=/* @__PURE__ */ new Map;valuesCache;writeRevision=0;anyNotifier=new Dh(()=>{});constructor(e){this.anyIgnoredKeys=e}get revision(){return this.writeRevision}faceOf(e){return this.channel(e).face}get(e){return this.rows.get(e)?.value}seqOf(e){let t=this.rows.get(e);return t?.kind===`sequenced`?t.seq:void 0}values(){return this.valuesCache===void 0&&(this.valuesCache=Object.freeze(Object.fromEntries([...this.rows].map(([e,t])=>[e,t.value])))),this.valuesCache}subscribeAny(e){return this.anyNotifier.subscribe(e)}apply(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<=r.seq?!1:r!==void 0&&Oh(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyLive(e,t,n){let r=this.rows.get(e);return r?.kind===`sequenced`&&n<r.seq?!1:r!==void 0&&Oh(r.value,t)?(this.rows.set(e,{kind:`sequenced`,value:r.value,seq:n}),this.writeRevision+=1,!1):(this.rows.set(e,{kind:`sequenced`,value:t,seq:n}),this.changed(e),!0)}applyCached(e){for(let t of Object.keys(e)){let n=this.rows.get(t);n?.kind!==`sequenced`&&(n!==void 0&&Oh(n.value,e[t])?this.writeRevision+=1:(this.rows.set(t,{kind:`cached`,value:e[t]}),this.changed(t)))}}seed(e,t,n){let r=e.values;for(let[e,t]of this.rows)t.kind!==`cached`||Object.hasOwn(r,e)||(this.rows.delete(e),this.changed(e));for(let n of Object.keys(r))t?.has(n)?this.applyLive(n,r[n],e.asOfSeq):this.apply(n,r[n],e.asOfSeq);for(let[t,i]of this.rows)Object.hasOwn(r,t)||n?.has(t)||i.kind===`sequenced`&&i.seq>e.asOfSeq||(this.rows.delete(t),this.changed(t))}discard(e){for(let t of e)this.rows.delete(t)&&this.changed(t)}clear(e){for(let[t,n]of[...this.rows])e?.has(t)===!0?this.rows.set(t,{kind:`cached`,value:n.value}):(this.rows.delete(t),this.changed(t))}changed(e){this.writeRevision+=1,this.valuesCache=void 0,this.channels.get(e)?.notifier.markDirty(),this.anyIgnoredKeys?.has(e)||this.anyNotifier.markDirty()}channel(e){let t=this.channels.get(e);if(t===void 0){let n=new Dh(()=>{});t={notifier:n,face:{getSnapshot:()=>this.rows.get(e)?.value,subscribe:e=>n.subscribe(e)}},this.channels.set(e,t)}return t}};let Ah=/* @__PURE__ */ new WeakMap;function jh(e){return e.length*2}function Mh(e,t){return jh(e)+jh(t)+64}function Nh(e){if(e===void 0||e.size===0)return 0;let t=64;for(let[n,r]of e)t+=Mh(n,r);return t}function Ph(e,t=0,n){if(e==null)return 0;switch(typeof e){case`string`:return jh(e);case`number`:case`boolean`:case`bigint`:case`symbol`:return 8;case`function`:return 64;case`object`:{if(t>=12)return 64;if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer)return e.byteLength+64;let r=Ah.get(e);if(r!==void 0)return r;if(n?.has(e))return 8;let i=n??/* @__PURE__ */ new Set;i.add(e);let a=64;try{if(Array.isArray(e)){a+=e.length*8;for(let n=0;n<e.length;n+=1)a+=Ph(e[n],t+1,i)}else if(e instanceof Map)for(let[n,r]of e)a+=64+Ph(n,t+1,i)+Ph(r,t+1,i);else if(e instanceof Set)for(let n of e)a+=8+Ph(n,t+1,i);else{let n=e;for(let e in n)Object.hasOwn(n,e)&&(a+=jh(e)+8+Ph(n[e],t+1,i))}}finally{i.delete(e)}return t===0&&n===void 0&&Object.isFrozen(e)&&Ah.set(e,a),a}default:return 0}}function Fh(e){let t=Ah.get(e);if(t!==void 0)return t;let n=Ph(e);return Ah.set(e,n),n}function Ih(e){let t=0;for(let n=0;n<e.length;n+=1)t+=8+Fh(e[n]);return t}function Lh(e){return e===void 0?0:64+jh(e.epoch)+Ih(e.records)}function Rh(e){let t=64,n;if(e.journal!==void 0){t+=64+jh(e.journal.epoch),n=/* @__PURE__ */ new Set;for(let r of e.journal.records)t+=8+Fh(r),n.add(r),typeof r.event==`object`&&r.event!==null&&n.add(r.event)}t+=64;for(let r of e.entries){if(t+=8,n!==void 0){if(n.has(r))continue;if(typeof r.event==`object`&&r.event!==null&&n.has(r.event)){t+=64;continue}}t+=Fh(r)}return t+=Nh(e.toolOutputs),t+=Ph(e.projections),t}var zh=class{readRemote;values=/* @__PURE__ */ new Map;pending=/* @__PURE__ */ new Map;maxBytes;totalBytes=0;constructor(e,t,n={}){if(this.readRemote=e,this.maxBytes=Math.max(0,n.maxBytes??8388608),t!==void 0)for(let[e,n]of t)this.remember(e,n)}get estimatedBytes(){return this.totalBytes}read(e){let t=JSON.stringify([e.sessionId,e.epoch,e.turn,e.seq,e.callId,e.part,e.version]),n=this.values.get(t);if(n!==void 0)return this.values.delete(t),this.values.set(t,n),Promise.resolve(n);let r=this.pending.get(t);if(r)return r;let i=this.readRemote(e).then(e=>{if(!e.ok)throw e.error;return this.remember(t,e.value.text),e.value.text}).finally(()=>{this.pending.delete(t)});return this.pending.set(t,i),i}remember(e,t){let n=this.values.get(e);n!==void 0&&(this.totalBytes-=Mh(e,n),this.values.delete(e));let r=Mh(e,t);if(!(r>this.maxBytes))for(this.values.set(e,t),this.totalBytes+=r;this.totalBytes>this.maxBytes&&this.values.size>0;){let t=this.values.entries().next().value;if(t[0]===e)break;this.values.delete(t[0]),this.totalBytes-=Mh(t[0],t[1])}}};function Bh(){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 Vh(e){return{kind:`leaf`,entries:e,length:e.length}}function Hh(e,t){return{kind:`concat`,left:e,right:t,length:e.length+t.length}}function Uh(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 Wh(e,t,n,r){let i;return{get entries(){return i??=Uh(e),i},hasMore:t,revision:n,change:r}}var Gh=class{listeners=/* @__PURE__ */ new Set;window=Vh([]);estimatedEntryBytes=0;snapshot=Wh(this.window,!1,0,{kind:`replace`,entries:[]});get estimatedBytes(){return this.estimatedEntryBytes}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}replace(e,t){this.window=Vh(e),this.estimatedEntryBytes=Ih(e),this.publish(t,{kind:`replace`,entries:e})}prepend(e,t){this.window=Hh(Vh(e),this.window),this.estimatedEntryBytes+=Ih(e),this.publish(t,{kind:`prepend`,entries:e})}append(e){let t=[e];this.window=Hh(this.window,Vh(t)),this.estimatedEntryBytes+=8+Fh(e),this.publish(this.snapshot.hasMore,{kind:`append`,entries:t})}settleAssistant(e,t){let n=Uh(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=Vh(n),this.estimatedEntryBytes=Ih(n),this.publish(this.snapshot.hasMore,{kind:`settle-assistant`,attemptId:e,...t===void 0?{}:{entry:t}})}publish(e,t){this.snapshot=Wh(this.window,e,this.snapshot.revision+1,t),(0,a.notifySubscribers)(this.listeners,`[session-controller] event feed`)}};function Kh(){let e=new Intl.DateTimeFormat().resolvedOptions().timeZone;if(typeof e!=`string`||e.length===0)throw Error(`browser time zone is unavailable`);return e}function qh(e){if(!Number.isSafeInteger(e))throw TypeError(`Assistant stream time must be a safe integer, got ${String(e)}`);return e}function Jh(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 Yh(e){let t=wh(e);if(t===void 0)throw TypeError(`Assistant stream chunk must be losslessly JSON-serializable`);return t}function Xh(e){let t=[];for(let n of e){let e=Zh(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 Zh(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`:{eg(t,[`type`,`time0`,`index`,`dt`,`texts`],t.type);let e=$h(t.texts,`${t.type} texts`);if(e.length===0)throw TypeError(`${t.type} texts must be non-empty`);return Qh(t,e.length,t.type),t}case`tool-call-chunks`:{eg(t,Object.hasOwn(t,`name`)?[`type`,`time0`,`index`,`dt`,`id`,`name`,`args`]:[`type`,`time0`,`index`,`dt`,`id`,`args`],t.type);let e=$h(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 Qh(t,e.length,t.type),t}case`chunk`:{eg(t,[`type`,`time`,`chunk`],`chunk`);let e=qh(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=Yh(t.chunk)}catch(e){throw TypeError(`Assistant stream raw chunk must be a lossless JSON object`,{cause:e})}return Th({type:`chunk`,time:e,chunk:n})}default:throw TypeError(`Unsupported Assistant stream record ${JSON.stringify(t.type)}`)}}function Qh(e,t,n){if(qh(e.time0),Jh(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 $h(e,t){if(!Array.isArray(e)||e.some(e=>typeof e!=`string`))throw TypeError(`${t} must be a string array`);return e}function eg(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 tg=class{activeAttempt;retainedAttempt;pending=/* @__PURE__ */ new Map;publishedSeqs=/* @__PURE__ */ new Set;durableCursor=-1;transientInGap=0;transientOrder=0;estimatedPendingBytes(){if(this.pending.size===0)return 0;let e=0;for(let t of this.pending.values())e+=8+Fh(t);return e}replace(e,t){this.pending.clear(),this.transientInGap=0,this.transientOrder=0,this.activeAttempt=void 0,this.retainedAttempt=void 0;let n=t?.activeAttempt;n!==void 0&&(this.activeAttempt={attemptId:n.attemptId,startedAfterSeq:n.startedAfterSeq,turn:n.turn,step:n.step,nextIndex:n.nextIndex});let r=[...e];if(this.publishedSeqs=new Set(r.map(e=>e.event.seq)),this.durableCursor=r.reduce((e,t)=>Math.max(e,t.event.seq),-1),n!==void 0){for(let[e,t]of Xh(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=ng(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 ng(e){return e.event.type===`assistant/message`||e.event.type===`assistant/attempt`?e:void 0}function rg(e){return{...e,asOfSeq:e.asOfSeq===-1?-1:p(e.asOfSeq)}}let ig={maxMessages:500,turnWindow:{minMessages:50,minTurns:2}},ag={...ig,turnWindow:{...ig.turnWindow,minMessages:200}};var og=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 tg;running=!1;address;parentAvailable;promptAttempted=!1;firstPromptPendingTurn=!1;blankBit=!0;removed=!1;promptError=null;inFlightPrompts=/* @__PURE__ */ new Map;lastAgentError=null;pendingSubmissions=[];submissionTarget;submissionSettlements=/* @__PURE__ */ new Map;events;projections;eventSource=new Gh;cachedProjectionBytesRevision=-1;cachedProjectionBytes=0;snapshotCache;notifier;actx;constructor(e,t,n={}){if(this.sessionId=e,this.remote=t,this.toolOutputs=new zh(e=>this.remote.session.toolOutput(e),n.cachedView?.toolOutputs),this.onEngaged=n.onEngaged,this.projections=n.projections??new kh,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 Dh(()=>{this.snapshotCache=this.buildSnapshot()}),this.snapshotCache=this.buildSnapshot(),this.stopObservingInbox=this.projections.faceOf(`inbox`).subscribe(()=>{this.observeSubmissionInbox()})}bindScope(e){if(this.actx!==void 0)throw Error(`session ${this.sessionId} already has a bound scope`);this.actx=e}unbindScope(){this.actx=void 0}beginSubmission(e){if(this.submissionTarget!==void 0)return this.submissionTarget.beginSubmission(e);let t=Bh(),n=this.running?e.mode===`steer`?`steering`:`queued`:`transcript`;return this.pendingSubmissions=[...this.pendingSubmissions,{requestId:t,placement:n,time:Date.now(),text:e.text,attachments:e.attachments}],this.submissionSettlements.set(t,{placement:n,expectedTurnId:e.mode===`steer`?this.activeTurnForSteering():null,onObserved:e.onObserved,onRetire:e.onRetire,observed:!1,retiring:!1}),this.promptAttempted=!0,this.notifier.markDirty(),{requestId:t,abandon:()=>{this.retireFailedSubmission(t)}}}handoffSubmissions(e){if(e=e.submissionOwner(),e===this||this.submissionTarget!==void 0)return[];let t=this.pendingSubmissions.map(e=>e.requestId);if(t.length===0)return t;e.pendingSubmissions=[...e.pendingSubmissions,...this.pendingSubmissions];for(let n of t){let t=this.submissionSettlements.get(n);t!==void 0&&e.submissionSettlements.set(n,t);let r=this.inFlightPrompts.get(n);r!==void 0&&e.inFlightPrompts.set(n,r)}this.submissionSettlements.clear(),this.submissionTarget=e,e.promptAttempted||=this.promptAttempted;for(let{event:t}of e.eventSource.getSnapshot().entries)e.observeSubmissionEvent(t);return e.observeSubmissionInbox(),e.notifier.markDirty(),t}submissionOwner(){return this.submissionTarget?.submissionOwner()??this}get hasInFlightPrompts(){return this.inFlightPrompts.size>0}activeTurnForSteering(){let e=this.projections.get(lm);return typeof e==`string`?e:null}async prompt(e,t,n,r){if(this.submissionTarget!==void 0)return this.submissionTarget.prompt(e,t,n,r);let i=r??Bh();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=Kh(),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:Kh()},n);s=a.ok?{ok:!0,value:{accepted:!0}}:a}let c=this.submissionOwner();return!s.ok&&s.error.code===`remote/outcome-unknown`&&c.hasObservedPrompt(i)&&(s={ok:!0,value:{accepted:!0}}),s.ok?(c.acceptPrompt(),s):(r!==void 0&&c.retireFailedSubmission(r),c.promptError={op:`send`,error:s.error,requestId:i},c.notifier.markDirty(),s)}finally{this.inFlightPrompts.get(i)===a&&this.inFlightPrompts.delete(i);let e=this.submissionOwner();e.inFlightPrompts.get(i)===a&&e.inFlightPrompts.delete(i),this.notifier.markDirty()}}acceptPrompt(){this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),this.onEngaged?.(this)}hasObservedPrompt(e){let t=t=>t.source.kind===`user`&&`rpcId`in t.source&&t.source.rpcId===e,n=this.projections.get(`inbox`);return this.inFlightPrompts.get(e)?.observed===!0||this.eventSource.getSnapshot().entries.some(({event:e})=>e.type===`user/message`&&t(e.data))||[...n?.[`next-turn`]??[],...n?.[`next-step`]??[]].some(t)}confirmPrompt(e){let t=this.inFlightPrompts.get(e);t&&(t.observed=!0),this.promptError?.op===`send`&&this.promptError.error.code===`remote/outcome-unknown`&&this.promptError.requestId===e&&(this.promptError=null,this.notifier.markDirty(),this.acceptPrompt())}async readAttachment(e){let t=await this.remote.session.attachment({sessionId:this.sessionId,attachmentId:e});if(!t.ok)return t;let n=atob(t.value.data),r=Uint8Array.from(n,e=>e.charCodeAt(0));return{ok:!0,value:{attachment:t.value.attachment,data:r}}}readToolOutput(e){return e.sessionId===this.sessionId?this.toolOutputs.read(e):Promise.reject(new o(`session/tool-output-stale`,`Tool output belongs to another session.`,{}))}async updateQueue(e,t){return this.remote.session.updateQueue({sessionId:this.sessionId,itemId:e,action:t})}async cancel(){let e=this.address,t=e===void 0?await this.remote.session.cancel({sessionId:this.sessionId}):await this.remote.subagents.interruptByParent(e.childSessionId,e.parentSessionId,`continuable`);return t.ok||(this.promptError={op:`stop`,error:t.error},this.notifier.markDirty()),t}async rename(e){let t=await this.remote.session.rename({sessionId:this.sessionId,title:e});if(!t.ok)return t;let n=p(t.value.seq);return this.projections.apply(`title`,t.value.title,n),{ok:!0,value:{title:t.value.title,seq:n}}}async command(e){let t=await this.remote.commands.execute(this.sessionId,e,[]);return t.ok?{ok:!0,value:{matched:t.value!==void 0}}:t}open(){if(this.openState===`open`)return Promise.resolve();if(this.openPromise!==null)return this.openPromise;let e=this.doOpen(this.openGeneration).finally(()=>{this.openPromise===e&&(this.openPromise=null)});return this.openPromise=e,e}async loadOlder(){if(this.openState!==`open`||!this.hasMore||this.loadingOlder)return;let e=this.events;if(e===void 0)return;let t=this.openGeneration;this.loadingOlder=!0,this.olderError=null,this.notifier.markDirty();try{await e.prepend({beforeSeq:this.baseSeq,...ig})}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,...ag}),n.beforeSeq>=e)return}}catch(e){(0,i.isRemoteFailure)(e)||console.error(`[session-controller] loadThrough failed:`,e)}finally{this.jumpTargetSeq=null,this.jumpPromise=null,this.pendingHistory=null,this.loadingOlder=!1,r===this.openGeneration&&n.pages.length>0&&this.prependWindow(n.pages.reverse().flat(),n.hasMore),this.notifier.markDirty()}})(),this.jumpPromise}async resync(){if(this.openState===`cold`)return;let e=++this.openGeneration,t=this.events;this.cachedJournal=t?.capture()??this.cachedJournal,this.events=void 0,await t?.dispose(),e===this.openGeneration&&(this.openPromise=null,this.openState=`cold`,this.openError=null,this.baseSeq=m(0),this.notifier.markDirty(),await this.open())}subscribe(e){return this.notifier.subscribe(e)}getSnapshot(){return this.notifier.ensureFresh(),this.snapshotCache}estimatedBytes(){let e=this.projections.revision;return this.cachedProjectionBytesRevision!==e&&(this.cachedProjectionBytes=Ph(this.projections.values()),this.cachedProjectionBytesRevision=e),(this.eventSource.estimatedBytes>0?this.eventSource.estimatedBytes:Lh(this.cachedJournal))+this.assistantStream.estimatedPendingBytes()+this.toolOutputs.estimatedBytes+this.cachedProjectionBytes}captureView(){if(this.lastSyncedAt===void 0||this.removed)return;let e=this.events?.capture()??this.cachedJournal;return{...e===void 0?{}:{journal:e},toolOutputs:new Map(this.toolOutputs.values),entries:this.eventSource.getSnapshot().entries,baseSeq:this.baseSeq,hasMore:this.hasMore,projections:this.projections.values(),lastSyncedAt:this.lastSyncedAt}}handleRunning(e){e&&this.blankBit&&(this.blankBit=!1,this.notifier.markDirty()),e&&(this.firstPromptPendingTurn=!1),this.running!==e&&(this.running=e,this.notifier.markDirty())}configureSubagent(e,t){let n=this.address?.parentSessionId===e?.parentSessionId&&this.address?.childSessionId===e?.childSessionId&&this.address?.mode===e?.mode;this.address=e,this.parentAvailable=t,!n&&this.openState!==`cold`?this.resync():this.notifier.markDirty()}handleSubagentParentAvailable(e){this.parentAvailable!==e&&(this.parentAvailable=e,this.notifier.markDirty())}handleBlank(e){e&&=this.projections.values().sessionListMetadata?.blank!==!1,e!==this.blankBit&&(e&&(this.promptAttempted||this.running)||(this.blankBit=e,this.notifier.markDirty()))}handleRemoved(){this.removed=!0,this.notifier.markDirty()}handleRestored(){this.removed&&(this.removed=!1,this.notifier.markDirty())}handleAgentError(e){this.lastAgentError=e,this.notifier.markDirty()}async dispose(){this.stopObservingInbox();for(let[e,t]of[...this.submissionSettlements])t.admitted===void 0?this.retireFailedSubmission(e):this.scheduleObservedRetirement(e,t.admitted);this.openGeneration++;let e=this.events;this.events=void 0,await e?.dispose()}async doOpen(e){this.openState=`loading`,this.openError=null,this.olderError=null,this.loadingOlder=!1,this.notifier.markDirty();let t=this.cachedJournal?.epoch,n=new pe(this.remote,this.sessionAddress(),{publish:r=>{e===this.openGeneration&&this.events===n&&(r.type===`replace`&&(t&&n.journalEpoch!==t&&this.projections.discard(um),t=n.journalEpoch),this.acceptEventChange(r))},failed:t=>{this.failEventStream(n,e,t)}},this.cachedJournal);this.events=n;try{if(await n.open(ig),e!==this.openGeneration||this.events!==n)return;this.cachedJournal=void 0,this.openState=`open`}catch(t){if(e!==this.openGeneration||this.events!==n)return;if(!(0,i.isRemoteFailure)(t))throw t;this.events=void 0,this.openState=`error`,this.openError=t}finally{e===this.openGeneration&&this.notifier.markDirty()}}acceptEventChange(e){switch(e.type){case`replace`:this.installWindow(e.entries,e.hasMore,e.page.projections===void 0?void 0:rg(e.page.projections),e.page.assistantStream,e.unchanged===!0);break;case`prepend`:this.prependWindow(e.entries,e.hasMore);break;case`append`:this.publishAssistantEntry(this.assistantStream.acceptDurable(e.entry));break;case`assistant-stream`:this.publishAssistantEntry(this.assistantStream.acceptFrame(e.frame));break;case`projection`:this.projections.applyLive(e.key,e.value,p(e.seq)),e.key===`subagent`&&this.address?.mode===`unknown`&&this.notifier.markDirty()}let t=this.lastSyncedAt;this.lastSyncedAt=Date.now(),(e.type!==`assistant-stream`||t===void 0)&&this.notifier.markFrameDirty()}installWindow(e,t,n,r,i=!1){let a=this.eventSource.getSnapshot(),o=this.assistantStream.replace(e,r),s=r?.activeAttempt!==void 0||o.some(e=>e.type===`transient`)||a.entries.some(e=>e.type===`transient`),c=i&&!s&&o.length===a.entries.length&&t===a.hasMore&&o.every((e,t)=>{let n=a.entries[t];return n?.type===e.type&&n.event.seq===e.event.seq});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),o.some(e=>e.event.type===`turn/start`)&&(this.firstPromptPendingTurn=!1),n!==void 0&&this.projections.seed(n,um),c||this.eventSource.replace(o,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 o)this.observeSubmissionEvent(e.event);if(n!==void 0){let e=n.values.inbox;for(let t of[`next-turn`,`next-step`])this.observeSubmissionInsertions(t,e?.[t]??[],0,n.asOfSeq)}this.notifier.markDirty()}publishAssistantEntry(e){if(e?.type===`rebaseline`){let e=this.events;queueMicrotask(()=>{e!==void 0&&this.events===e&&e.restart()})}else if(e?.type===`settlement`)this.eventSource.settleAssistant(e.attemptId,e.entry),this.observeSubmissionEvent(e.entry.event);else if(e?.type===`abandonment`)this.eventSource.settleAssistant(e.attemptId);else if(e?.type===`publish`){let t=this.appendLive(e.entry);e.retireAttemptId!==void 0&&this.eventSource.settleAssistant(e.retireAttemptId),t&&this.notifier.markDirty()}else e?.type===`transient`&&this.eventSource.append(e.entry)}prependWindow(e,t){if(this.pendingHistory!==null){let n=this.pendingHistory;n.beforeSeq=e[0]===void 0?n.beforeSeq:m(e[0].event.seq),n.hasMore=t,n.pages.push(e);return}let n=this.hasMore;this.baseSeq=e[0]===void 0?this.baseSeq:m(e[0].event.seq),this.hasMore=t,this.eventSource.prepend(e,t),n!==t&&this.notifier.markDirty();for(let{event:t}of e)if(t.type===`user/message`)this.observeSubmissionMessage(t.data,!0);else if(t.type===`agent/inbox/spliced`)for(let{source:e}of t.data.inserted)e.kind===`user`&&`rpcId`in e&&this.confirmPrompt(e.rpcId)}appendLive(e){let t=e.event,n=this.firstPromptPendingTurn;return t.type===`turn/start`&&(this.firstPromptPendingTurn=!1),this.eventSource.append(e),this.observeSubmissionEvent(t),n!==this.firstPromptPendingTurn}observeSubmissionEvent(e){if(e.type===`user/message`)this.observeSubmissionMessage(e.data,!0);else if(this.submissionSettlements.size!==0||this.inFlightPrompts.size!==0||this.promptError?.requestId!==void 0){if(e.type===`agent/inbox/spliced`){let{target:t,start:n,removedCount:r=0,inserted:i,outcome:a}=e.data;for(let[o,s]of this.submissionSettlements){let c=s.receipt;if(c?.target!==t||c.index===null||c.seq>=e.seq)continue;let l=c.index>=n&&c.index<n+r;l&&a===`canceled`?this.retireFailedSubmission(o):s.receipt={...c,seq:e.seq,index:l?null:c.index<n?c.index:c.index+i.length-r}}this.observeSubmissionInsertions(t,i,n,e.seq);for(let e of i)this.observeSubmissionMessage(e,!1,t)}else if(e.type===`request/context`||e.type===`turn/end`)for(let[t,n]of this.submissionSettlements)n.admitted===void 0&&n.receipt?.index===null&&n.receipt.seq<e.seq&&this.retireFailedSubmission(t)}}observeSubmissionInsertions(e,t,n,r){for(let[i,a]of t.entries()){let t=a.source;if(t.kind!==`user`||!(`rpcId`in t))continue;this.confirmPrompt(t.rpcId);let o=this.submissionSettlements.get(t.rpcId);o===void 0||o.placement===`queued`||o.retiring||(o.receipt?.seq??-1)>r||(o.receipt={target:e,seq:r,index:n+i,attachments:cg(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=cg(e.content),this.notifySubmissionObserved(i,i.admitted),this.retireAdmittedSubmission(r.rpcId)):(i.placement===`queued`||n===`next-turn`)&&this.scheduleObservedRetirement(r.rpcId,cg(e.content)))}retireAdmittedSubmission(e){let t=this.submissionSettlements.get(e);if(t?.admitted===void 0)return;let n=t.receipt;n?.index===null&&(this.projections.seqOf(`inbox`)??-1)<n.seq||this.scheduleObservedRetirement(e,t.admitted)}observeSubmissionInbox(){if(this.submissionSettlements.size===0&&this.inFlightPrompts.size===0&&this.promptError?.requestId===void 0)return;let e=this.projections.get(`inbox`);if(e===void 0)return;let t=this.projections.seqOf(`inbox`);for(let n of[`next-turn`,`next-step`]){t!==void 0&&this.observeSubmissionInsertions(n,e[n],0,t);for(let t of e[n])this.observeSubmissionMessage(t,!1,n)}for(let e of this.submissionSettlements.keys())this.retireAdmittedSubmission(e)}notifySubmissionObserved(e,t){e.observed||(e.observed=!0,e.onObserved?.(t))}scheduleObservedRetirement(e,t){let n=this.submissionSettlements.get(e);n===void 0||n.retiring||(n.retiring=!0,this.notifySubmissionObserved(n,t),sg(()=>{this.finishSubmission(e,{reason:`observed`,attachments:t})}))}retireFailedSubmission(e){if(this.submissionTarget!==void 0){this.submissionTarget.retireFailedSubmission(e);return}let t=this.submissionSettlements.get(e);t===void 0||t.retiring||t.admitted!==void 0||(t.retiring=!0,this.finishSubmission(e,{reason:`failed`}))}finishSubmission(e,t){if(this.submissionTarget!==void 0){this.submissionTarget.finishSubmission(e,t);return}let n=this.submissionSettlements.get(e);
|
|
128
128
|
/* v8 ignore next -- retiring latches before every schedule, so one settlement never finishes twice. */
|
|
129
|
-
n!==void 0&&(this.submissionSettlements.delete(e),this.pendingSubmissions=this.pendingSubmissions.filter(t=>t.requestId!==e),this.notifier.markDirty(),n.onRetire?.(t))}failEventStream(e,t,n){if(t===this.openGeneration&&this.events===e){if(!(0,i.isRemoteFailure)(n))throw n;this.openGeneration++,this.cachedJournal=e.capture(),this.events=void 0,this.openPromise=null,this.openState=`error`,this.openError=n,e.dispose(),this.notifier.markDirty()}}buildSnapshot(){let e=this.projections.values().subagent;return{sessionId:this.sessionId,pendingSubmissions:this.pendingSubmissions,running:this.running,subagent:this.address===void 0?null:{address:this.address.mode===`unknown`&&e!=null?{...this.address,mode:e.mode}:this.address,...this.parentAvailable===void 0?{}:{parentAvailable:this.parentAvailable}},removed:this.removed,openState:this.openState,...this.lastSyncedAt===void 0?{}:{lastSyncedAt:this.lastSyncedAt},openError:this.openError,hasMore:this.hasMore,loadingOlder:this.loadingOlder,olderError:this.olderError,promptError:this.promptError,blank:this.blankBit,lastAgentError:this.lastAgentError,promptAttempted:this.promptAttempted,awaitingFirstTurn:this.firstPromptPendingTurn}}sessionAddress(){return this.address===void 0?{kind:`session`,sessionId:this.sessionId}:{kind:`subagent`,...this.address}}};function Qh(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function $h(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 eg=class{views=/* @__PURE__ */ new Map;maxEntries;maxBytes;estimateBytes;cachedBytes=0;constructor(e={}){this.maxEntries=Math.max(0,e.maxEntries??8),this.maxBytes=Math.max(0,e.maxBytes??25165824),this.estimateBytes=e.estimateBytes??kh}get size(){return this.views.size}get totalBytes(){return this.cachedBytes}take(e){let t=this.views.get(e);if(t!==void 0)return this.views.delete(e),this.cachedBytes-=t.bytes,t.view}remember(e,t){let n=this.views.get(e);n!==void 0&&(this.views.delete(e),this.cachedBytes-=n.bytes);let r=Math.max(0,this.estimateBytes(t));if(this.maxEntries===0||r>this.maxBytes)return[e];this.views.set(e,{view:t,bytes:r}),this.cachedBytes+=r;let i=[];for(;this.views.size>this.maxEntries||this.cachedBytes>this.maxBytes;){let t=this.views.entries().next().value;if(t[0]===e)break;this.views.delete(t[0]),this.cachedBytes-=t[1].bytes,i.push(t[0])}return i}delete(e){let t=this.views.get(e);t!==void 0&&(this.views.delete(e),this.cachedBytes-=t.bytes)}clear(){this.views.clear(),this.cachedBytes=0}};function tg(e){return e===-1?-1:p(e)}let ng=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]),rg=/* @__PURE__ */ new Set([...tm,`codexhostTurnTimes`,`codexhostUsage`,`contextPressure`,`contextBreakdown`,`inbox`,`queueState`,`turnOutline`,`sessionStats`,`compacting`,`goal`,`agentPreset`,`plan`,`todos`,`permissions`,`nativePermissions`,`modelSelection`,`draftSelectionExplicit`,`attachmentInput`,`imageLimits`,`sentMessageEdit`]);var ig=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new eg;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;workspaceOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;workspaceStartCursor;workspaceHistory=/* @__PURE__ */ new Map;activeWorkspacePage;activeListCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];projectionSnapshotCache=/* @__PURE__ */ new Map;projectionsBySessionCache={};notifier=new vh(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r)for(let t of this.recentViews.remember(e,r))this.projectionStores.get(t)?.discard(tm);return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.resetListQueries(),this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new Zh(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 bh(rg);let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markFrameDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.revision;this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.revision===a&&r.clear():r.seed({...t.value,asOfSeq:tg(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.resetListQueries(),this.refreshList())}resetListQueries(){this.nextCursor=void 0,this.workspaceStartCursor=void 0,this.workspaceHistory=/* @__PURE__ */ new Map,this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null}hasSummary(e){return this.summaries.some(t=>t.sessionId===e)}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){if(e===void 0)return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve();let t=this.workspaceHistory,n=t.get(e);if(n?.pending)return n.pending;let r=n?n.cursor:this.workspaceStartCursor;if(!r||this.disposed)return Promise.resolve();let i={cursor:r,state:`loading`};return t.set(e,i),this.notifier.markDirty(),i.pending=(async()=>{t===this.workspaceHistory&&await this.refreshList(r,e)})().finally(()=>{delete i.pending,t===this.workspaceHistory&&this.notifier.markDirty()}),i.pending}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null){if(t===this.activeWorkspacePage&&e===this.activeListCursor)return this.listInflight;let n=this.workspaceHistory;return this.listInflight.catch(()=>void 0).then(()=>{if(n===this.workspaceHistory)return this.refreshList(e,t)})}let n=this.includeArchived;this.activeWorkspacePage=t,this.activeListCursor=e;let r=t===void 0?void 0:this.workspaceHistory.get(t);r||(this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0);let a=e=>{r?r.state=`retry`:(this.listState=`error`,this.listError=e)},o=this.summaries,s=[];return this.listMutations=s,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==s)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),a=new Set(i.value.items.map(e=>e.sessionId)),c=r!==void 0||i.value.nextCursor!==void 0,l=i.value.nextCursor??null;if(r){let e=new Set(this.summaries.map(e=>e.sessionId)),t=i.value.items.filter(t=>!t.blank&&!e.has(t.sessionId));for(let e of t)this.workspaceOnlyIds.add(e.sessionId);r.cursor=l,r.state=l?t.length>0?`search`:`continue`:`done`}else{for(let e of a)this.workspaceOnlyIds.delete(e);(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=l),e===void 0&&this.workspaceStartCursor==null&&(this.workspaceStartCursor=l)}let u=[...i.value.items,...o.filter(e=>!a.has(e.sessionId)&&(c||!n&&t.has(e.sessionId)))],d=this.listPhase===`pending`?u:rh(o,u,e=>e.sessionId),f=/* @__PURE__ */ new Set;for(let e of s)e.kind===`remove`&&f.add(e.sessionId);for(let e of d)e.running&&!f.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let p=s.reduce(ag,d);this.summaries=p;let m=new Set(p.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(a.has(e)||!m.has(e))&&this.summaryOnlyIds.delete(e);for(let e of this.workspaceOnlyIds)m.has(e)||this.workspaceOnlyIds.delete(e);let ee=this.retainedIds(p);for(let e of this.engagedSessions)this.pruneEngagement(e,ee);r||(this.listState=`idle`,this.listPhase=`ready`),this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===s&&(this.headRefreshRevision+=1)}else a(i.error)}catch(e){if(this.listMutations!==s)return;if(r)r.state=`retry`;else if((0,i.isRemoteFailure)(e))a(e);else throw e}finally{this.listMutations===s&&(this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t={...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.matchProjectDefault?{matchProjectDefault:!0}:{},...e.roleSlug===void 0?{}:{roleSlug:e.roleSlug}},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=og(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:og(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq))&&this.notifier.markDirty(),n}mergeSummary(e){let t=this.recordMutation({kind:`upsert`,summary:e},`frame`);return this.updateParentAvailability(),t}recordMutation(e,t=`microtask`){if(this.disposed)return!1;this.listMutations?.push(e);let n=ag(this.summaries,e);return n!==this.summaries&&(this.summaries=n,t===`frame`?this.notifier.markFrameDirty():this.notifier.markDirty(),!0)}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq))&&!rg.has(e.key)&&this.notifier.markFrameDirty()}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=tg(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,tm)}this.notifier.markFrameDirty()}handleSessionAdded(e,t=!0){let n=t&&this.summaryOnlyIds.delete(e.sessionId),r=t&&this.workspaceOnlyIds.delete(e.sessionId),i=this.mergeSummary(e);(n||r)&&!i&&this.notifier.markFrameDirty(),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let a=this.sessions.get(e.sessionId);a?.handleRestored(),a?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=tg(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:ch(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){let t=this.summaryOnlyIds.delete(e),n=this.workspaceOnlyIds.delete(e),r=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`),i=this.recordMutation(r?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e},`frame`),a=!1;if(r){let t=this.sessions.get(e);a=t?.getSnapshot().running===!0,t?.handleRunning(!1)}else this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved();let o=this.projectionStores.get(e)?.values().subagentCatalog,s=!r&&(o===void 0||o.length===0)&&this.projectionStores.delete(e);this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e);let c=this.projectionLoads.delete(e);!i&&(t||n||s||c||a)&&this.notifier.markFrameDirty();for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e);let n=this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0},`frame`);this.updateParentAvailability();let r=this.sessions.get(e),i=r?.getSnapshot().running;r?.handleRunning(t),!n&&r!==void 0&&i!==t&&this.notifier.markFrameDirty()}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t},`frame`)}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(ng);this.resetListQueries(),this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=_h(this.summaries.map(e=>{let t=this.projectionStores.get(e.sessionId),n=t?.get(`title`),r=t?.values(),i=r?.sessionListMetadata;return{...e,blank:this.effectiveBlank(e)&&i?.blank!==!1,updatedAt:Math.max(e.updatedAt,i?.lastPromptAt??0),...typeof n==`string`&&n!==``?{title:n}:{},...r===void 0?{}:{projectionValues:r}}})).map(e=>{let t=this.entryCache.get(e.sessionId);return t!==void 0&&t.updatedAt===e.updatedAt&&t.running===e.running&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e);let n=this.projectionSnapshotCache.size!==this.projectionStores.size;for(let[e,t]of this.projectionStores){let r=t.values(),i=this.projectionLoads.get(e),a=i?.state??`idle`,o=i?.error??null,s=this.projectionSnapshotCache.get(e);(s===void 0||s.values!==r||s.state!==a||s.error!==o)&&(this.projectionSnapshotCache.set(e,{values:r,state:a,error:o}),n=!0)}if(n){for(let e of this.projectionSnapshotCache.keys())this.projectionStores.has(e)||this.projectionSnapshotCache.delete(e);this.projectionsBySessionCache=Object.fromEntries(this.projectionSnapshotCache)}return{items:this.itemsCache,hasMore:!!this.nextCursor,canSearchWorkspaceHistory:!!this.workspaceStartCursor,workspaceHistory:Object.fromEntries([...this.workspaceHistory].map(([e,t])=>[e,t.pending?`loading`:t.state])),workspaceOnlyIds:[...this.workspaceOnlyIds],headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:this.projectionsBySessionCache}}};function ag(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.findIndex(e=>e.sessionId===t.summary.sessionId);if(n===-1)return[t.summary,...e];let r=e[n],i={...r,blank:r.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...r.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...r.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...r.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};if(i.cwd===r.cwd&&i.parentSessionId===r.parentSessionId&&i.origin===r.origin&&i.blank===r.blank&&i.agentAvailable===r.agentAvailable&&i.running===r.running)return e;let a=[...e];return a[n]=i,a}case`remove`:return e.findIndex(e=>e.sessionId===t.sessionId)===-1?e:e.filter(e=>e.sessionId!==t.sessionId);case`status`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(r.running===t.running&&r.agentAvailable===t.agentAvailable&&(!t.running||!r.blank))return e;let i=[...e];return i[n]={...r,running:t.running,agentAvailable:t.agentAvailable,blank:r.blank&&!t.running},i}case`activity`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!(t.updatedAt>r.updatedAt))return e;let i=[...e];return i[n]={...r,updatedAt:t.updatedAt},i}case`engaged`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!r.blank)return e;let i=[...e];return i[n]={...r,blank:!1},i}}}function og(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var sg=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},cg=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 lg(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 ug(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 dg(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let fg=Object.freeze({referenceCount:0,retainedBy:dg({})});async function pg(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 mg=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]);pg(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()}},hg=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;projectedItemCache=/* @__PURE__ */ new Map;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new ig(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}handoffSubmissions(e,t){let n=this.scopes.get(e)?.session;if(n===void 0||e===t||n.getSnapshot().pendingSubmissions.length===0&&!n.hasInFlightPrompts)return;let r=this.retain(t,{source:`controllerOperation`}),i=this.retain(e,{source:`controllerOperation`}),a=this.manager.get(t),o=new Set(n.handoffSubmissions(a)),s=[],c=!1,l=()=>{if(!c){c=!0;for(let e of s)e();r.release(),i.release()}},u=()=>{!n.hasInFlightPrompts&&!a.getSnapshot().pendingSubmissions.some(e=>o.has(e.requestId))&&l()};s.push(a.subscribe(u),n.subscribe(u)),r.ready.catch(l),i.ready.catch(l),u()}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}async loadSummary(e){await this.manager.loadSummary(e),this.closed||this.projectList()}syncSummary(e){return this.list.getSnapshot().byId[e]===void 0?this.closed||!this.manager.hasSummary(e)?!1:(this.projectList(),this.list.getSnapshot().byId[e]!==void 0):!0}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new sg(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 cg(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,ug(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}estimatedBytes(e){return this.scopes.get(e)?.session.estimatedBytes()??0}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:dg({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new mg(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?fg:Object.freeze({referenceCount:r,retainedBy:dg(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??fg}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:fg,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,state:c,error:l,errorPage:u,headRefreshRevision:d,summaryOnlyIds:f}=this.manager.getListSnapshot(),p=[],m={};for(let e of t){p.push(e.sessionId);let t=this.retentionSnapshot(e.sessionId).retainedBy,n=this.projectedItemCache.get(e.sessionId);if(n!==void 0&&n.entry===e&&n.retainedBy===t){m[e.sessionId]=n.summary;continue}let r={id:e.sessionId,displayTitle:lg(e.title,e.cwd,e.sessionId),running:e.running,retainedBy:t,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};this.projectedItemCache.set(e.sessionId,{entry:e,retainedBy:t,summary:r}),m[e.sessionId]=r}if(this.projectedItemCache.size>t.length)for(let e of this.projectedItemCache.keys())m[e]===void 0&&this.projectedItemCache.delete(e);for(let e in r){let t=r[e]?.values.subagentCatalog;if(t!==void 0&&t.length!==0)for(let n of t){let t=n.id,r=m[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?m[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(m[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}}for(let[t,n]of this.scopes){if(m[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;m[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:p,byId:m,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,loading:c===`loading`,listError:l?.message??null,listErrorPage:u,headRefreshRevision:d??0,summaryOnlyIds:f??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let gg=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function _g(e){let t=e.remote,n=e.get(`connection`),r=new hg(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=Ih,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=sg,n.SessionEventStream=pe,n.SessionForkError=cg,n.apply=_g,n.createScope=_e,n.createSessionControlStream=fe,n.inject=gg,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 sg(e){typeof requestAnimationFrame==`function`?requestAnimationFrame(()=>{e()}):setTimeout(e,0)}function cg(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 lg=class{views=/* @__PURE__ */ new Map;maxEntries;maxBytes;estimateBytes;cachedBytes=0;constructor(e={}){this.maxEntries=Math.max(0,e.maxEntries??8),this.maxBytes=Math.max(0,e.maxBytes??25165824),this.estimateBytes=e.estimateBytes??Rh}get size(){return this.views.size}get totalBytes(){return this.cachedBytes}take(e){let t=this.views.get(e);if(t!==void 0)return this.views.delete(e),this.cachedBytes-=t.bytes,t.view}remember(e,t){let n=this.views.get(e);n!==void 0&&(this.views.delete(e),this.cachedBytes-=n.bytes);let r=Math.max(0,this.estimateBytes(t));if(this.maxEntries===0||r>this.maxBytes)return[e];this.views.set(e,{view:t,bytes:r}),this.cachedBytes+=r;let i=[];for(;this.views.size>this.maxEntries||this.cachedBytes>this.maxBytes;){let t=this.views.entries().next().value;if(t[0]===e)break;this.views.delete(t[0]),this.cachedBytes-=t[1].bytes,i.push(t[0])}return i}delete(e){let t=this.views.get(e);t!==void 0&&(this.views.delete(e),this.cachedBytes-=t.bytes)}clear(){this.views.clear(),this.cachedBytes=0}};function ug(e){return e===-1?-1:p(e)}let dg=/* @__PURE__ */ new Set([`title`,`codexhostUsage`,`contextPressure`,`contextBreakdown`]),fg=/* @__PURE__ */ new Set([...um,`codexhostTurnTimes`,`codexhostUsage`,`contextPressure`,`contextBreakdown`,`inbox`,`queueState`,`turnOutline`,`sessionStats`,`compacting`,`goal`,`agentPreset`,`plan`,`todos`,`permissions`,`nativePermissions`,`modelSelection`,`draftSelectionExplicit`,`attachmentInput`,`imageLimits`,`sentMessageEdit`]);var pg=class{remote;sessions=/* @__PURE__ */ new Map;recentViews=new lg;sessionDisposals=/* @__PURE__ */ new Set;engagedSessions=/* @__PURE__ */ new Set;disposed=!1;projectionStores=/* @__PURE__ */ new Map;summaries=[];summaryOnlyIds=/* @__PURE__ */ new Set;workspaceOnlyIds=/* @__PURE__ */ new Set;listState=`idle`;listPhase=`pending`;listError=null;listRequestIsMore=!1;headRefreshRevision=0;listInflight=null;includeArchived=!1;nextCursor;workspaceStartCursor;workspaceHistory=/* @__PURE__ */ new Map;activeWorkspacePage;activeListCursor;listMutations=null;addresses=/* @__PURE__ */ new Map;projectionLoads=/* @__PURE__ */ new Map;projectionInflight=/* @__PURE__ */ new Map;listSnapshotCache;entryCache=/* @__PURE__ */ new Map;itemsCache=[];projectionSnapshotCache=/* @__PURE__ */ new Map;projectionsBySessionCache={};notifier=new Dh(()=>{this.listSnapshotCache=this.buildListSnapshot()});constructor(e){this.remote=e,this.listSnapshotCache=this.buildListSnapshot()}resolveTarget(e){let t=typeof e==`string`?e:e.childSessionId,n=typeof e==`string`?this.subagentAddress(t):e;if(typeof e==`string`&&!this.sessions.has(t)&&!this.summaries.some(e=>e.sessionId===t)&&n===void 0)throw Error(`sessions.retain: unknown session ${t}`);return n!==void 0&&this.addresses.set(t,n),this.sessions.get(t)?.configureSubagent(n,n===void 0?void 0:this.agentAvailable(n.parentSessionId)),t}subagentAddress(e){let t=this.addresses.get(e);if(t!==void 0)return t;for(let t of this.projectionStores.keys()){let n=this.projectionStores.get(t)?.values().subagentCatalog?.find(t=>t.id===e);if(n!==void 0)return{parentSessionId:t,childSessionId:e,mode:n.mode}}}drop(e,t){let n=this.sessions.get(e);if(n!==t)return Promise.resolve();let r=n.captureView();if(r)for(let t of this.recentViews.remember(e,r))this.projectionStores.get(t)?.discard(um);return this.sessions.delete(e),this.addresses.delete(e),this.pruneEngagement(e,this.retainedIds(this.summaries)),this.startSessionDisposal(n)}async dispose(){this.disposed=!0,this.resetListQueries(),this.engagedSessions.clear();let e=[...this.projectionInflight.values()];for(let{controller:t}of e)t.abort();this.projectionInflight.clear(),await Promise.all(e.map(e=>e.promise));let t=[...this.sessions.values()];this.sessions.clear(),this.recentViews.clear(),this.addresses.clear();for(let e of t)this.startSessionDisposal(e);await this.drainSessionDisposals()}startSessionDisposal(e){let t=e.dispose();return this.sessionDisposals.add(t),t.then(()=>{this.sessionDisposals.delete(t)},()=>{this.sessionDisposals.delete(t)}),t}async drainSessionDisposals(){for(;this.sessionDisposals.size>0;)await Promise.allSettled([...this.sessionDisposals])}get(e){let t=this.sessions.get(e);if(t===void 0){t=this.createSession(e),this.sessions.set(e,t);let n=this.summaries.find(t=>t.sessionId===e);if(n!==void 0)t.handleBlank(this.effectiveBlank(n)),t.handleRunning(n.running);else{let n=this.addresses.get(e);(n===void 0?void 0:this.projectionStores.get(n.parentSessionId)?.values().subagentCatalog?.find(t=>t.id===e))===void 0?t.handleBlank(!0):(t.handleBlank(!1),t.handleRunning(!1))}}return t}createSession(e){let t=this.addresses.get(e),n=t===void 0?void 0:this.agentAvailable(t.parentSessionId);return new og(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 kh(fg);let n=t;t.subscribeAny(()=>{n.values().sessionListMetadata?.blank===!1&&this.sessions.get(e)?.handleBlank(!1),this.notifier.markFrameDirty()}),this.projectionStores.set(e,t)}return t}refreshProjections(e){let t=this.projectionInflight.get(e);if(t!==void 0)return t.promise;if(this.projectionLoads.get(e)?.state===`ready`)return Promise.resolve();let n=new AbortController,r=this.projectionStore(e),a=r.revision;this.projectionLoads.set(e,{state:`loading`,error:null}),this.notifier.markDirty();let o=(async()=>{try{let t=await this.remote.session.projections({sessionId:e},n.signal);if(n.signal.aborted)return;t.ok?(t.value===null?r.revision===a&&r.clear():r.seed({...t.value,asOfSeq:ug(t.value.asOfSeq)}),this.projectionLoads.set(e,{state:`ready`,error:null})):this.projectionLoads.set(e,{state:`error`,error:t.error})}catch(t){if(n.signal.aborted)return;if(!(0,i.isRemoteFailure)(t))throw t;this.projectionLoads.set(e,{state:`error`,error:t})}finally{n.signal.aborted||(this.projectionInflight.delete(e),this.notifier.markDirty())}})();return this.projectionInflight.set(e,{promise:o,controller:n}),o}agentAvailable(e){return this.summaries.find(t=>t.sessionId===e)?.agentAvailable??(this.listPhase!==`ready`&&void 0)}updateParentAvailability(){for(let[e,t]of this.addresses){let n=this.agentAvailable(t.parentSessionId);n!==void 0&&this.sessions.get(e)?.handleSubagentParentAvailable(n)}}setIncludeArchived(e){return this.includeArchived===e?this.listInflight??Promise.resolve():(this.includeArchived=e,this.resetListQueries(),this.refreshList())}resetListQueries(){this.nextCursor=void 0,this.workspaceStartCursor=void 0,this.workspaceHistory=/* @__PURE__ */ new Map,this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null}hasSummary(e){return this.summaries.some(t=>t.sessionId===e)}async loadSummary(e){if(this.summaries.some(t=>t.sessionId===e))return;let t=await this.remote.session.list({sessionId:e});if(!t.ok)throw t.error;if(!this.disposed)for(let e of t.value.items)this.summaries.some(t=>t.sessionId===e.sessionId)||this.summaryOnlyIds.add(e.sessionId),this.handleSessionAdded(e,!1)}loadMore(e){if(e===void 0)return this.nextCursor?this.refreshList(this.nextCursor):Promise.resolve();let t=this.workspaceHistory,n=t.get(e);if(n?.pending)return n.pending;let r=n?n.cursor:this.workspaceStartCursor;if(!r||this.disposed)return Promise.resolve();let i={cursor:r,state:`loading`};return t.set(e,i),this.notifier.markDirty(),i.pending=(async()=>{t===this.workspaceHistory&&await this.refreshList(r,e)})().finally(()=>{delete i.pending,t===this.workspaceHistory&&this.notifier.markDirty()}),i.pending}refreshList(e,t){if(this.disposed)return Promise.resolve();if(this.listInflight!==null){if(t===this.activeWorkspacePage&&e===this.activeListCursor)return this.listInflight;let n=this.workspaceHistory;return this.listInflight.catch(()=>void 0).then(()=>{if(n===this.workspaceHistory)return this.refreshList(e,t)})}let n=this.includeArchived;this.activeWorkspacePage=t,this.activeListCursor=e;let r=t===void 0?void 0:this.workspaceHistory.get(t);r||(this.listState=`loading`,this.listError=null,this.listRequestIsMore=e!==void 0);let a=e=>{r?r.state=`retry`:(this.listState=`error`,this.listError=e)},o=this.summaries,s=[];return this.listMutations=s,this.notifier.markDirty(),this.listInflight=(async()=>{try{let i=await this.remote.session.list({includeArchived:n,...e?{cursor:e,...t?{workspaceId:t}:{}}:{}});if(this.listMutations!==s)return;if(i.ok){let t=new Set(i.value.archivedSessionIds),a=new Set(i.value.items.map(e=>e.sessionId)),c=r!==void 0||i.value.nextCursor!==void 0,l=i.value.nextCursor??null;if(r){let e=new Set(this.summaries.map(e=>e.sessionId)),t=i.value.items.filter(t=>!t.blank&&!e.has(t.sessionId));for(let e of t)this.workspaceOnlyIds.add(e.sessionId);r.cursor=l,r.state=l?t.length>0?`search`:`continue`:`done`}else{for(let e of a)this.workspaceOnlyIds.delete(e);(e!==void 0||this.nextCursor===void 0)&&(this.nextCursor=l),e===void 0&&this.workspaceStartCursor==null&&(this.workspaceStartCursor=l)}let u=[...i.value.items,...o.filter(e=>!a.has(e.sessionId)&&(c||!n&&t.has(e.sessionId)))],d=this.listPhase===`pending`?u:fh(o,u,e=>e.sessionId),f=/* @__PURE__ */ new Set;for(let e of s)e.kind===`remove`&&f.add(e.sessionId);for(let e of d)e.running&&!f.has(e.sessionId)&&this.engagedSessions.add(e.sessionId);let p=s.reduce(mg,d);this.summaries=p;let m=new Set(p.map(e=>e.sessionId));for(let e of this.summaryOnlyIds)(a.has(e)||!m.has(e))&&this.summaryOnlyIds.delete(e);for(let e of this.workspaceOnlyIds)m.has(e)||this.workspaceOnlyIds.delete(e);let ee=this.retainedIds(p);for(let e of this.engagedSessions)this.pruneEngagement(e,ee);r||(this.listState=`idle`,this.listPhase=`ready`),this.updateParentAvailability();for(let e of this.summaries){let t=this.sessions.get(e.sessionId);t!==void 0&&(t.handleBlank(this.effectiveBlank(e)),t.handleRunning(e.running))}for(let e of i.value.items)e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections);e===void 0&&this.listMutations===s&&(this.headRefreshRevision+=1)}else a(i.error)}catch(e){if(this.listMutations!==s)return;if(r)r.state=`retry`;else if((0,i.isRemoteFailure)(e))a(e);else throw e}finally{this.listMutations===s&&(this.activeWorkspacePage=void 0,this.activeListCursor=void 0,this.listMutations=null,this.listInflight=null,this.notifier.markDirty())}})(),this.listInflight}async search(e,t){let n=await this.remote.session.search({query:e},t);return n.ok?{ok:!0,value:{items:n.value.items.filter(e=>this.summaries.some(t=>t.sessionId===e.sessionId)),hasMore:n.value.hasMore}}:n}async create(e={}){let t={...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.matchProjectDefault?{matchProjectDefault:!0}:{},...e.roleSlug===void 0?{}:{roleSlug:e.roleSlug}},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=hg(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:hg(r.error);return i!==void 0&&this.recordMutation({kind:`placeholder`,summary:{agentAvailable:!0,sessionId:i,updatedAt:Date.now(),running:!1,blank:!0,parentSessionId:e.sessionId,...n?.cwd===void 0?{}:{cwd:n.cwd}}}),r}async rename(e,t){let n=await this.remote.session.rename({sessionId:e,title:t});return n.ok&&this.projectionStore(e).apply(`title`,n.value.title,p(n.value.seq))&&this.notifier.markDirty(),n}mergeSummary(e){let t=this.recordMutation({kind:`upsert`,summary:e},`frame`);return this.updateParentAvailability(),t}recordMutation(e,t=`microtask`){if(this.disposed)return!1;this.listMutations?.push(e);let n=mg(this.summaries,e);return n!==this.summaries&&(this.summaries=n,t===`frame`?this.notifier.markFrameDirty():this.notifier.markDirty(),!0)}subscribe(e){return this.notifier.subscribe(e)}getListSnapshot(){return this.notifier.ensureFresh(),this.listSnapshotCache}projectionValues(e){return this.projectionStores.get(e)?.values()}handleControlFrame(e){e.type===`baseline`?this.replaceControlBaseline(e.value):this.projectionStore(e.sessionId).applyLive(e.key,e.value,p(e.seq))&&!fg.has(e.key)&&this.notifier.markFrameDirty()}replaceControlBaseline(e){for(let[t,n]of Object.entries(e.projections)){let e=this.projectionStore(t),r=ug(n.asOfSeq);e.seed({...n,asOfSeq:r},void 0,um)}this.notifier.markFrameDirty()}handleSessionAdded(e,t=!0){let n=t&&this.summaryOnlyIds.delete(e.sessionId),r=t&&this.workspaceOnlyIds.delete(e.sessionId),i=this.mergeSummary(e);(n||r)&&!i&&this.notifier.markFrameDirty(),!this.disposed&&e.running&&this.engagedSessions.add(e.sessionId);let a=this.sessions.get(e.sessionId);a?.handleRestored(),a?.handleBlank(this.effectiveBlank(e)),e.projections!==void 0&&this.applyListBlock(e.sessionId,e.projections)}applyListBlock(e,t){let n=this.projectionStore(e);switch(t.kind){case`sequenced`:{let e=ug(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:_h(t.kind,`session list projection block kind`)}}handleSessionRemoved(e){let t=this.summaryOnlyIds.delete(e),n=this.workspaceOnlyIds.delete(e),r=this.subagentAddress(e)!==void 0||this.summaries.some(t=>t.sessionId===e&&t.origin===`subagent`),i=this.recordMutation(r?{kind:`status`,sessionId:e,running:!1,agentAvailable:!1}:{kind:`remove`,sessionId:e},`frame`),a=!1;if(r){let t=this.sessions.get(e);a=t?.getSnapshot().running===!0,t?.handleRunning(!1)}else this.recentViews.delete(e),this.sessions.get(e)?.handleRemoved();let o=this.projectionStores.get(e)?.values().subagentCatalog,s=!r&&(o===void 0||o.length===0)&&this.projectionStores.delete(e);this.pruneEngagement(e,this.retainedIds(this.summaries)),this.projectionInflight.get(e)?.controller.abort(),this.projectionInflight.delete(e);let c=this.projectionLoads.delete(e);!i&&(t||n||s||c||a)&&this.notifier.markFrameDirty();for(let[t,n]of this.addresses)n.parentSessionId===e&&this.sessions.get(t)?.handleSubagentParentAvailable(!1)}handleSessionStatus(e,t){!this.disposed&&t&&this.engagedSessions.add(e);let n=this.recordMutation({kind:`status`,sessionId:e,running:t,agentAvailable:!0},`frame`);this.updateParentAvailability();let r=this.sessions.get(e),i=r?.getSnapshot().running;r?.handleRunning(t),!n&&r!==void 0&&i!==t&&this.notifier.markFrameDirty()}handleSessionActivity(e,t){this.recordMutation({kind:`activity`,sessionId:e,updatedAt:t},`frame`)}handleSessionError(e,t){this.sessions.get(e)?.handleAgentError(t)}handleConnected(){for(let e of this.sessions.values())e.getSnapshot().openState===`error`&&e.resync();for(let e of this.projectionStores.values())e.clear(dg);this.resetListQueries(),this.refreshList();let e=new Set(this.projectionLoads.keys());for(let t of this.sessions.keys()){let n=this.addresses.get(t);n!==void 0&&e.add(n.parentSessionId)}for(let{controller:e}of this.projectionInflight.values())e.abort();this.projectionInflight.clear(),this.projectionLoads.clear();for(let t of e)this.refreshProjections(t)}buildListSnapshot(){let e=Eh(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.agentAvailable===e.agentAvailable&&t.blank===e.blank&&t.parentSessionId===e.parentSessionId&&t.cwd===e.cwd&&t.origin===e.origin&&t.title===e.title&&t.depth===e.depth&&t.projectionValues===e.projectionValues?t:(this.entryCache.set(e.sessionId,e),e)}),t=new Set(e.map(e=>e.sessionId));for(let e of this.entryCache.keys())t.has(e)||this.entryCache.delete(e);e.length===this.itemsCache.length&&e.every((e,t)=>e===this.itemsCache[t])||(this.itemsCache=e);let n=this.projectionSnapshotCache.size!==this.projectionStores.size;for(let[e,t]of this.projectionStores){let r=t.values(),i=this.projectionLoads.get(e),a=i?.state??`idle`,o=i?.error??null,s=this.projectionSnapshotCache.get(e);(s===void 0||s.values!==r||s.state!==a||s.error!==o)&&(this.projectionSnapshotCache.set(e,{values:r,state:a,error:o}),n=!0)}if(n){for(let e of this.projectionSnapshotCache.keys())this.projectionStores.has(e)||this.projectionSnapshotCache.delete(e);this.projectionsBySessionCache=Object.fromEntries(this.projectionSnapshotCache)}return{items:this.itemsCache,hasMore:!!this.nextCursor,canSearchWorkspaceHistory:!!this.workspaceStartCursor,workspaceHistory:Object.fromEntries([...this.workspaceHistory].map(([e,t])=>[e,t.pending?`loading`:t.state])),workspaceOnlyIds:[...this.workspaceOnlyIds],headRefreshRevision:this.headRefreshRevision,summaryOnlyIds:[...this.summaryOnlyIds],state:this.listState,phase:this.listPhase,error:this.listError,errorPage:this.listError?this.listRequestIsMore?`more`:`head`:null,projectionsBySession:this.projectionsBySessionCache}}};function mg(e,t){switch(t.kind){case`upsert`:case`placeholder`:{let n=e.findIndex(e=>e.sessionId===t.summary.sessionId);if(n===-1)return[t.summary,...e];let r=e[n],i={...r,blank:r.blank&&t.summary.blank,...t.kind===`upsert`?{agentAvailable:t.summary.agentAvailable,running:t.summary.running}:{},...r.cwd===void 0&&t.summary.cwd!==void 0?{cwd:t.summary.cwd}:{},...r.parentSessionId===void 0&&t.summary.parentSessionId!==void 0?{parentSessionId:t.summary.parentSessionId}:{},...r.origin===void 0&&t.summary.origin!==void 0?{origin:t.summary.origin}:{}};if(i.cwd===r.cwd&&i.parentSessionId===r.parentSessionId&&i.origin===r.origin&&i.blank===r.blank&&i.agentAvailable===r.agentAvailable&&i.running===r.running)return e;let a=[...e];return a[n]=i,a}case`remove`:return e.findIndex(e=>e.sessionId===t.sessionId)===-1?e:e.filter(e=>e.sessionId!==t.sessionId);case`status`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(r.running===t.running&&r.agentAvailable===t.agentAvailable&&(!t.running||!r.blank))return e;let i=[...e];return i[n]={...r,running:t.running,agentAvailable:t.agentAvailable,blank:r.blank&&!t.running},i}case`activity`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!(t.updatedAt>r.updatedAt))return e;let i=[...e];return i[n]={...r,updatedAt:t.updatedAt},i}case`engaged`:{let n=e.findIndex(e=>e.sessionId===t.sessionId);if(n===-1)return e;let r=e[n];if(!r.blank)return e;let i=[...e];return i[n]={...r,blank:!1},i}}}function hg(e){return e.code===`session/workspace-attach-failed`?e.details.sessionId:void 0}var gg=class extends Error{rpcError;requestedSessionId;name=`SessionCreateError`;constructor(e,t){super(`session create failed: ${e.code}: ${e.message}`),this.rpcError=e,this.requestedSessionId=t}},_g=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 vg(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 yg(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 bg(e){return Object.setPrototypeOf(e,null),Object.freeze(e)}let xg=Object.freeze({referenceCount:0,retainedBy:bg({})});async function Sg(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 Cg=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]);Sg(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()}},wg=class{rootCtx;searchResultLimit=20;list;manager;scopes=/* @__PURE__ */ new Map;retainObservers=/* @__PURE__ */ new Map;scopeDrops=/* @__PURE__ */ new Set;projectedItemCache=/* @__PURE__ */ new Map;closed=!1;constructor(e,t){this.rootCtx=e,this.manager=new pg(t),this.list=(0,a.createSnapshotStore)({ids:[],byId:{},phase:`pending`,headRefreshRevision:0,summaryOnlyIds:[],projectionsBySession:{}});let n=this.manager.subscribe(()=>{this.projectList()});e.effect(()=>async()=>{this.closed=!0,n();let e=[...this.scopes];this.scopes.clear();for(let[,t]of e)t.live=!1,t.session.unbindScope();let t=this.manager.dispose();for(let[t,n]of e)this.startScopeDrop(t,n),this.publishRetention(t);await this.drainScopeDrops(),await t},`session-controller.client.sessions`),e.reflect.provide(`sessions`,this,void 0)}retain(e,t){let{source:n,signal:r}=t;if(r?.throwIfAborted(),this.closed)throw Error(`Session Controller is disposed`);let i=this.manager.resolveTarget(e),a=this.retainScope(i,n);try{return a.attachOpening(this.manager.get(i).open(),r),a}catch(e){throw a.release(),e}}handoffSubmissions(e,t){let n=this.scopes.get(e)?.session;if(n===void 0||e===t||n.getSnapshot().pendingSubmissions.length===0&&!n.hasInFlightPrompts)return;let r=this.retain(t,{source:`controllerOperation`}),i=this.retain(e,{source:`controllerOperation`}),a=this.manager.get(t),o=new Set(n.handoffSubmissions(a)),s=[],c=!1,l=()=>{if(!c){c=!0;for(let e of s)e();r.release(),i.release()}},u=()=>{!n.hasInFlightPrompts&&!a.getSnapshot().pendingSubmissions.some(e=>o.has(e.requestId))&&l()};s.push(a.subscribe(u),n.subscribe(u)),r.ready.catch(l),i.ready.catch(l),u()}async using(e,t,n){let r=this.retain(e,t);try{return await r.ready,await n(r)}finally{r.release()}}retainInfo(e){let t=this.retainObservers.get(e);if(t===void 0){let n=/* @__PURE__ */ new Set;t={listeners:n,published:this.retentionSnapshot(e),source:{getSnapshot:()=>this.retentionSnapshot(e),subscribe:e=>(n.add(e),()=>{n.delete(e)})}},this.retainObservers.set(e,t)}return t.source}async retryHistory(e){let t=this.scopes.get(e);if(!t?.live)throw Error(`Session history is no longer retained`);await t.session.resync()}subagentAddress(e){return this.manager.subagentAddress(e)}refreshProjections(e){return this.manager.refreshProjections(e)}refresh(){return this.manager.refreshList()}async loadSummary(e){await this.manager.loadSummary(e),this.closed||this.projectList()}syncSummary(e){return this.list.getSnapshot().byId[e]===void 0?this.closed||!this.manager.hasSummary(e)?!1:(this.projectList(),this.list.getSnapshot().byId[e]!==void 0):!0}loadMore(e){return this.manager.loadMore(e)}setIncludeArchived(e){return this.manager.setIncludeArchived(e)}search(e,t){return this.manager.search(e,t)}handleControlFrame(e){this.manager.handleControlFrame(e)}handleSessionAdded(e){this.manager.handleSessionAdded(e)}handleSessionRemoved(e){this.manager.handleSessionRemoved(e)}handleSessionStatus(...e){this.manager.handleSessionStatus(...e)}handleSessionActivity(...e){this.manager.handleSessionActivity(...e)}handleSessionError(...e){this.manager.handleSessionError(...e)}handleConnected(){this.manager.handleConnected()}async create(e={}){let t=await this.manager.create(e);if(!t.ok)throw new gg(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 _g(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,yg(t));if(!e.ok)throw Error(`fork child rename failed: ${e.error.code}: ${e.error.message}`)}return r}scope(e){return this.scopes.get(e)?.ctx}retainAgentScope(e){if(this.closed)throw Error(`Session Controller is disposed`);return this.retainScope(e,`gateway`)}scopeOf(e){return ve(e)}sessionOf(e){let t=ve(e);if(t===void 0)return;let n=this.scopes.get(t);return n!==void 0&&ye(n.ctx)===ye(e)?n.binding.session:void 0}binding(e){return this.scopes.get(e)?.binding}estimatedBytes(e){return this.scopes.get(e)?.session.estimatedBytes()??0}retainScope(e,t){let n=this.scopes.get(e)??this.materializeScope(e),r=n.retention;n.retention=Object.freeze({referenceCount:r.referenceCount+1,retainedBy:bg({...r.retainedBy,[t]:(r.retainedBy[t]??0)+1})});let i=new Cg(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?xg:Object.freeze({referenceCount:r,retainedBy:bg(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??xg}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:xg,live:!0};return this.scopes.set(e,i),n.effect(()=>()=>{this.retireScope(e,i,!1)},`session-controller: exact generation`),i}projectList(){let e=this.list.getSnapshot().byId,{items:t,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,state:c,error:l,errorPage:u,headRefreshRevision:d,summaryOnlyIds:f}=this.manager.getListSnapshot(),p=[],m={};for(let e of t){p.push(e.sessionId);let t=this.retentionSnapshot(e.sessionId).retainedBy,n=this.projectedItemCache.get(e.sessionId);if(n!==void 0&&n.entry===e&&n.retainedBy===t){m[e.sessionId]=n.summary;continue}let r={id:e.sessionId,displayTitle:vg(e.title,e.cwd,e.sessionId),running:e.running,agentAvailable:e.agentAvailable,retainedBy:t,blank:e.blank,updatedAt:e.updatedAt,...e.projectionValues===void 0?{}:{projectionValues:e.projectionValues},...e.title===void 0?{}:{title:e.title},...e.cwd===void 0?{}:{cwd:e.cwd},...e.parentSessionId===void 0?{}:{parentId:e.parentSessionId},...e.origin===void 0?{}:{origin:e.origin}};this.projectedItemCache.set(e.sessionId,{entry:e,retainedBy:t,summary:r}),m[e.sessionId]=r}if(this.projectedItemCache.size>t.length)for(let e of this.projectedItemCache.keys())m[e]===void 0&&this.projectedItemCache.delete(e);for(let e in r){let t=r[e]?.values.subagentCatalog;if(t!==void 0&&t.length!==0)for(let n of t){let t=n.id,r=m[t],i=r?.projectionValues??this.manager.projectionValues(t),a=i?.title,o=typeof a==`string`&&a!==``?a:void 0,s=o??n.label??t;r===void 0?m[t]={id:t,displayTitle:s,parentId:e,origin:`subagent`,running:this.scopes.get(t)?.session.getSnapshot().running??!1,blank:!1,updatedAt:0,retainedBy:this.retentionSnapshot(t).retainedBy,...i===void 0?{}:{projectionValues:i},...o===void 0?{}:{title:o}}:(r.displayTitle!==s||r.projectionValues!==i)&&(m[t]={...r,displayTitle:s,...i===void 0?{}:{projectionValues:i}})}}for(let[t,n]of this.scopes){if(m[t]!==void 0)continue;let r=this.manager.subagentAddress(t);if(r===void 0)continue;let i=e[t],a=n.session.getSnapshot(),o=this.manager.projectionValues(t),s=o?.title,c=typeof s==`string`&&s!==``?s:i?.title;m[t]={...i??{id:t,displayTitle:t,updatedAt:0},running:a.running,retainedBy:n.retention.retainedBy,blank:a.blank,parentId:r.parentSessionId,origin:`subagent`,...o===void 0?{}:{projectionValues:o},...c===void 0?{}:{title:c,displayTitle:c}}}this.list.set({ids:p,byId:m,phase:n,projectionsBySession:r,hasMore:i,canSearchWorkspaceHistory:a,workspaceHistory:o,workspaceOnlyIds:s,loading:c===`loading`,listError:l?.message??null,listErrorPage:u,headRefreshRevision:d??0,summaryOnlyIds:f??[]})}startScopeDrop(e,t,n=!0,r=this.manager.drop(e,t.session)){let i=this.dropScope(t,n,r);this.scopeDrops.add(i),i.then(()=>{this.scopeDrops.delete(i)},()=>{this.scopeDrops.delete(i)})}async drainScopeDrops(){for(;this.scopeDrops.size>0;)await Promise.allSettled([...this.scopeDrops])}async dropScope(e,t,n){await Promise.allSettled([n,...t?[e.fiber.dispose()]:[]])}};let Tg=[`connection`,`fileUpload`,`typert`,`remote`,`remote.commands`,`remote.session`,`remote.subagents`];function Eg(e){let t=e.remote,n=e.get(`connection`),r=new wg(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=Gh,n.SESSION_SEARCH_RESULT_LIMIT=20,n.SESSION_SEARCH_SNIPPET_MAX_CODE_POINTS=240,n.SessionCreateError=gg,n.SessionEventStream=pe,n.SessionForkError=_g,n.apply=Eg,n.createScope=_e,n.createSessionControlStream=fe,n.inject=Tg,n.scopeOf=ve,t.exports}});
|