diff --git a/assets/agent-team/icon.png b/assets/agent-team/icon.png new file mode 100644 index 00000000..2a545184 Binary files /dev/null and b/assets/agent-team/icon.png differ diff --git a/external_plugins/agent-team/.mcp.json b/external_plugins/agent-team/.mcp.json new file mode 100644 index 00000000..db48285c --- /dev/null +++ b/external_plugins/agent-team/.mcp.json @@ -0,0 +1,24 @@ +{ + "mcpServers": { + "team-daemon": { + "type": "stdio", + "command": "node", + "args": [ + "${ZCODE_PLUGIN_ROOT}/runtime/team-daemon.mjs" + ], + "cwd": "${ZCODE_PROJECT_DIR}", + "env": { + "TEAM_PLUGIN_DATA": "${ZCODE_PLUGIN_DATA}", + "TEAM_PROJECT_DIR": "${ZCODE_PROJECT_DIR}", + "TEAM_PLUGIN_ROOT": "${ZCODE_PLUGIN_ROOT}", + "TEAM_MAX_MEMBERS": "${user_config.maxMembers}", + "TEAM_MAX_TASKS": "${user_config.maxTasks}", + "TEAM_MAX_MESSAGE_BYTES": "${user_config.maxMessageBytes}", + "TEAM_DISPOSAL_TIMEOUT_MS": "${user_config.disposalTimeoutMs}", + "TEAM_INTERRUPT": "${user_config.interrupt}", + "TEAM_LEAD_MODE": "${user_config.leadMode}" + }, + "timeoutMs": 3600000 + } + } +} \ No newline at end of file diff --git a/external_plugins/agent-team/.zcode-plugin/plugin.json b/external_plugins/agent-team/.zcode-plugin/plugin.json new file mode 100644 index 00000000..3ccf0abc --- /dev/null +++ b/external_plugins/agent-team/.zcode-plugin/plugin.json @@ -0,0 +1,70 @@ +{ + "name": "agent-team", + "version": "0.5.5-rc.1", + "description": "智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。", + "description_i18n": { + "en": "Agent Teams: spawn and coordinate teammate sessions with a shared task board and member messaging.", + "zh-CN": "智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。" + }, + "author": { + "name": "Vincent Zuo", + "url": "https://github.com/Vincent-chk" + }, + "license": "MIT", + "userConfig": { + "maxMembers": { + "title": "最大成员数", + "description": "团队内 teammate 数量上限(不含 Lead;含 failed)。", + "type": "number", + "default": 8 + }, + "maxTasks": { + "title": "最大任务数", + "description": "任务板任务数量上限。", + "type": "number", + "default": 256 + }, + "maxMessageBytes": { + "title": "单条消息字节上限", + "description": "成员间单条消息的最大字节数。", + "type": "number", + "default": 65536 + }, + "disposalTimeoutMs": { + "title": "处置超时(毫秒)", + "description": "团队处置(teammate 结算与回收)的超时时间。", + "type": "number", + "default": 5000 + }, + "interrupt": { + "title": "启用 interrupt_agent 工具", + "description": "关闭后团队成员只拿到 8 个工具(interrupt_agent 不注册);域 API 仍可用。", + "type": "boolean", + "default": true + }, + "leadMode": { + "title": "Lead 模式", + "description": "off:完全关闭智能体团队(不注入团队上下文、不注册团队工具);auto(默认):按需委派——建队前默认单 agent 直接处理,建队后按委派价值判断是否走团队流程;always:始终主动编排(自主拆活/组队/分派/独立验收)。旧值 orchestrator/collaborator 将按 auto 处理。取值:off、auto 或 always。", + "type": "string", + "default": "auto" + } + }, + "skills": "skills", + "commands": "commands", + "hooks": "hooks/hooks.json", + "ui": { + "surfaces": [ + { + "id": "agent-team-panel", + "title": { + "zh-CN": "智能体团队", + "en": "Agent Team" + }, + "icon": "users", + "server": "team-daemon", + "resourceUri": "ui://agent-team/team-panel.html", + "availability": "session" + } + ] + } +} diff --git a/external_plugins/agent-team/CHANGELOG.md b/external_plugins/agent-team/CHANGELOG.md new file mode 100644 index 00000000..abd84b9c --- /dev/null +++ b/external_plugins/agent-team/CHANGELOG.md @@ -0,0 +1,210 @@ +# Changelog + +## 0.5.5-rc.1 — 2026-11-04 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +本地候选版,尚未发布;ZCode 实机 E2E 待用户验收。 + +- Lead 在 wait_agent 本轮结果中收取成员消息,已空闲成员的待收结果优先于 noProgress;与 hook 共用持久回执,协调者与代理统一领取,批量结果按响应字节预算分批返回。 +- 回执部分写入失败时保留结果正文并提示可能重投,避免已写回执屏蔽正文;取消、失锁与成员隔离继续保护待收消息。 +- 首次建队即补齐完整按需协作规范;每个委派单元先建任务,成员 get/claim 后执行、完成并交付,由 Lead 记录独立验收。纯文本交付不再依赖额外中转文件。 +- 包含 0.5.4 后工作区的恢复与失锁补修:缺启动回执时不重复拉起;pending 自动复核与持久预算;预检失败不留孤儿登记;异步模型同步、启动、投递、处置与接任均受代次保护。 + +## 0.5.4 — 2026-11-03 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **创建结果确认与保守接任**:活协调者/存活未知时不再因心跳超龄抢占,确认退出仍保留 ≤5s 接任;失锁立即撤销旧代次,不执行失锁 drain/checkpoint 或旧 watcher 写入。 +- **持久创建意图与固定命令恢复**:origin 在登记/宿主调用前保存 requestId、首轮输入、固定 commandId 与预分配 anchor;app-server 超时先查询原命令,unknown 保持待确认,不换号重建。 +- **pending 工具契约**:已受理未确认返回 provisioning 成员与 `creation:"pending"`;原已确认响应不变。失锁取消、探针异常、helper 回执缺失与 active 本地提交失败不再编造成员失败;恢复预算跨接任持久保留。 +- **发布一致性**:`/team` 带参直接执行且不输出摘要;发布绑定显式冻结 SHA、tag、远端基线和包指纹,检查命令文本与打包/解包一致。 +- 本轮验收:全量 **936/936**;真实双进程活持有者不接任/死亡接任、失锁撤销、固定命令丢响应与重启恢复、启动回执窗口及 pending/断连关联通过;S9 14 项与构建产物门通过。 + +## 0.5.3 — 2026-11-02 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **降级提示改为事实描述(D30 修订,重要)**:0.5.2 的提示里含 `do not call spawn_teammate`,该句进入对话历史后**不可撤销**——实测中用户切到第三方模型、撤回提示也已注入,模型仍服从早期禁令、全程不调用 spawn,表现为「切成第三方还是不能用」。现改为只陈述当前事实 + 明确恢复条件("此刻调用会因继承限制失败;一旦换成自配第三方模型就正常可用,无需额外确认"),并**禁止任何禁止性祈使句**(`scripts/text-audit.mjs` 加反向断言)。撤回提示同时显式声明早前提示失效,并要求用一行告知用户「队友已可用」(此前模型心里知道但不告知,用户感知不到恢复)。 +- **`/team` 带参数时真的建队执行**:`/team`(无参)仍严格只读输出状态摘要;`/team <任务>` 先输出摘要,再按角色 spawn 成员、必要时建共享任务并划写域、等齐结果后汇总,`spawn_teammate` 失败时明确说明原因并改为直接完成。此前 `/team <任务>` 只读状态后模型自行代劳,用户连输两次都没建队(2026-11-02 体感问题)。 +- **`/team` 取数改走 MCP 主通道,禁止猜目录**:成员/任务只来自 `list_agents` + `team_task_list`(团队身份由宿主 `_meta.session_id` 解析);`teamDir` 只用于渲染可选 CLI 段且优先取 `TEAM_PLUGIN_DATA`。删除了「扫 `agent-team*/teams/` 最近修改目录」的兜底——多副本并存时它会跨数据根读到别的插件的团队(实测导致 Lead 依据错误成员列表空转)。 +- **协调者锁双信号存活判定(偏差 D32)**:真会话取证(`sess_cabd748c`)显示协调者锁会把**活着的持有者**误判死亡——心跳是 1s 同步写盘,daemon 事件循环被同步 fsync 卡住时心跳文件停滞超过 4.5s 过期阈值,竞争者即抢锁;抢锁瞬间新协调者构造即跑 provisioning 对账,把两个仍在正常供给的成员误杀(面板红字 `provisioning did not leave a…` / `app-server rpc timeout: v4/…`)。现抢锁前先看持有者 PID 是否存活:真崩溃(PID 已死)→ 立即接任(kill -9 ≤5s SLA 不变);stalled-but-alive → 记 `steal-deferred` 审计并宽限 3s 复核、15s 硬上限兜底;锁文件增 `startedAt` + `ps -o etime=` 防 PID 复用;心跳首写失败补审计、renew 坏写重试一次。 +- **provisioning 对账宽限(偏差 D33)**:新协调者上任即跑对账,而 in-flight spawn 的 origin 记录在 createChild 之后才落盘(实测窗口 7–46s)→ 旧逻辑误杀。现按 journal 事件年龄(<60s)跳过瞬态判定并 10s 后复核;年龄超宽限或恢复抛错照旧定案(真故障不被掩盖)。 +- 本地验收:**908 用例 / 75 文件**全部通过;崩溃护栏 f29/crash-matrix/real-host 原样全绿(takeover 实测 4270–4305ms ≤5s,SLA 未退化);文本审计 26 项、S9 14 项、`npm run check` 与构建产物门通过。S3 的 C1–C5 子进程仍受 exFAT 环境挂账影响(stage-2 矩阵 12 点含 takeover-mid 在 S3 内通过)。 + +## 0.5.2 — 2026-11-02 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **会话开始即知晓 + 首轮对账(issue #5 / 偏差 D30)**:`startup` 路径原本读不到库(hook 先于会话行落库约 1.4s,三源必空),0.5.1 的说法「首轮提问即注入」对全新会话并不成立。0.5.2 改为优先读宿主 SessionStart 载荷自带的 `model`(`"providerId/modelId"`)判定套餐档,全新会话**在用户敲第一条消息之前就知晓**;老宿主无该字段自动回落三源探针。已通知后每轮提问与库对账(首轮 UserPromptSubmit 时宿主已写好选模条目),一旦确认已非套餐模型即**一次性撤回**(`SOLO_RETRACT_NOTE`)——覆盖「首条消息前切第三方」与「会话中途切模型」两种自愈路径;三源全空(无证据)绝不撤回。 +- **`hook` 日志增记 `model_category`**(account/builtin/custom/null,只记形态不记模型明细),把「宿主是否下发 model」从源码推断变成运行可实证。 +- **构建产物语法门(偏差 D31)**:`build.mjs` 写完产物即对 7 个 JS(含 0 字节判定)与 2 个 HTML(`` 收尾)校验,失败整体重建 ≤3 次;`release.mjs` 对 staging 与解包树各再校验一次并核缺件清单。外置卷偶发的 ~1MB bundle 落盘撕裂此前只能靠人工 `node --check` 兜,`--verify-repro` 也拦不住(两份同坏产物哈希一致)。 +- **新增 S9 确定性剧本**:直跑出厂 `runtime/team-hooks.mjs`,12 项检查覆盖 startup 载荷注入、去重、第三方不误报、首轮「仅选模条目无消息」真实时序、源 1/源 3 各自正反例、off 档、无证据不撤回、误报撤回恰一次、resume 撤回;夹具强制隔离在临时库(不写宿主库)。 +- 本地验收:**900 用例 / 75 文件**全部通过;覆盖率口径(排除自带阈值的性能基准 `f32.test.ts`,其单跑 903ms 达标)74 文件 / 898 用例,91.65/85.24/92.65/93.47 四项门槛全过;文本审计 26 项、S9 14 项、`npm run check` 通过。 +- 真会话实测(订阅套餐模型):新会话零输入时锚已落盘(早于首条消息 2.3s,`model_category=account` 证明宿主确已下发 model),复杂目标全程 0 次 `spawn_teammate`;会话中途切到第三方模型后,下一轮提问即写入 `soloRetractedAt`(撤回恰一次,通知锚完整保留)。未桌面实测的部分(首条消息前切模型无误报、fork/派生回归)由 S9 的确定性检查覆盖——本机 ZCode 为补丁版(adhoc 签名、无 TeamIdentifier),官方 Computer Use helper 拒绝为非合规签名进程启动,无法做桌面驱动实测。 + +## 0.5.1 — 2026-11-02 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **订阅模型降级自干(issue #5 / 偏差 D29)**:Lead 的已确认模型为官方套餐(`account:*`/`builtin:*`,CLI 子进程拿不到凭据、spawn 必败)时,hook 在 SessionStart 或首轮提问**每会话一次**注入单 agent 兜底提示——Lead 直接自己干全部工作、不再浪费轮次试建队;措辞非永久(中途切第三方模型后 spawn 成功即恢复正常用队)。检测乐观(三源全空/读库失败绝不误报)。 +- spawn 失败报错与 `spawn_teammate` 工具描述同步补「或由 Lead 直接完成该工作」出路。 +- 本地验收:**882 用例 / 75 文件**全部通过(新增探针 6 例 + hook 注入/去重/合并 7 例);覆盖率 91.6/85.05/92.5/93.35 门槛不变;`npm run check`、文本审计 25 项通过;本机订阅模型真会话实证。 + +## 0.5.0 — 2026-11-02 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **Lead 模式三档化(issue #9 / 偏差 D28)**:`leadMode` 从二值(orchestrator/collaborator)改为三档—— + - `auto`(**新默认**,按需委派):会话未建过队时不注入任何模式段(普通单 agent 语义,简单任务直接处理,不再为委派而委派);该会话曾创建过团队后(`members/` 存在成员目录即持久判定,含 inactive/failed)注入**按需段**(委派价值门槛 + 正反例:问答/单文件小改/调研汇总由 Lead 直接处理并说明一句理由,多角色并行/写域互斥/长任务 fork/点名成员走团队流程),验收与等待语义不变; + - `always`:保留原 orchestrator 主动编排行为(自主拆活、组队、分派、独立验收); + - `off`:完全关闭——hook 不注入任何团队上下文(策略/身份/收件箱/Stop block 全停,session-map 与轮次记录等内部副作用保留),daemon 不注册团队工具(tools/list 0 个,直连调用被拒)。 +- **旧值迁移**:`orchestrator`/`collaborator` 统一按 `auto` 处理(daemon 记迁移告警);runtime-config 升 v2——0.5.0 前落盘的旧文件 leadMode 视为过期回落默认,升级用户不被锁进激进档;宿主 config 直读层归一后判定(旧值→auto 接受)。 +- **auto 档中途首建队**:SessionStart 只在 startup/resume 触发,首成员 `spawn_teammate` 成功结果尾部以独立 text 块附一行 `FIRST_SPAWN_NOTE` 指引(不改结果 JSON),后续 resume 自然补全按需段。 +- **三通道同步**:工具描述去档位措辞改模式中立(spawn_teammate / team_task_update 两处);`skills/team-coordination/SKILL.md` 编排节重写为三档(含按需段逐字引用);文本审计扩为 24 项(D26/D28 三态两文本)。 +- e2e:S7 改显式 `always` 跑编排旅程;新增 S8 auto 默认链冒烟(简单任务不建队 + 注入无模式段 + runtime-config=auto);U-O1 重写为 auto 默认链口径(db 级无模式段断言),U-O2 改旧值迁移场景。 +- 本地验收:**869 用例 / 73 文件**全部通过(基线 849 + 20);覆盖率 statements **91.65%**、branches **85.19%**、functions **92.58%**、lines **93.42%**,门槛不变;`npm run check` 与文本审计 24 项通过。 + +## 0.4.3 — 2026-11-01 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- 产物目录 `dist/` 全局更名为 `runtime/`(ZCode 官方插件市场仓库不收录 `external_plugins/*/dist/` 构建产物目录名):`.mcp.json`、`hooks/hooks.json`、`/team` 命令文档与全部构建/测试/演练脚本同步改引用,行为无变化。 +- 面向插件市场发布适配:`README.md` 重写为英文用户文档,新增等价中文 `README_CN.md`(随包分发),两份均新增「网络访问、依赖与副作用」申报章节;manifest author 补充主页 URL。 +- 面板入口文档落到具体路径(issue #8):README 给出官方宿主通用路径(「+」→「查看所有插件」→「个人」→「智能体团队」→「打开」)与宿主含「新标签页」入口时的快捷路径;`/team` 桌面指引同步具体化。 +- 本地验收:**849 用例 / 72 文件**全部通过;`npm run check`(typecheck + ZCode 清单校验 + daemon 冒烟 12 项)通过;覆盖率与既有门槛不变。真机验收记录见 PR 材料。 + +## 0.4.2 — 2026-10-26 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- 修正成员实际选模判断:宿主选模条目缺失或损坏时重新应用 Lead 选择,历史调用记录不能证明下一轮 `--resume` 的模型。 +- 首轮启动前仍复核 Lead 最新选择,处理培育期间换模;刚应用的选择未变时免重复 RPC。 +- 真实子进程非零退出按临时故障退避;失败前已排队的消息合并进失败记录,避免被误当成新消息触发额外重试。 +- 创建预检保留原有重名、名额错误顺序;单次继承判定复用同一目录快照,删除未使用的重试返回值与后台重复抑制日志。 +- 校正既有 v6 验收材料的证据范围:真实模型调用通过不代表真实输入框与 `/model` 切模交互已经验收。 +- 本地验收:**849 用例 / 72 文件**全部通过;覆盖率 statements **91.61%**、branches **85.15%**、functions **92.55%**、lines **93.4%**,原门槛不变。构建、类型检查、ZCode 清单校验、daemon 冒烟、四方版本校验通过;视觉 76 页零漂移、伴生交互 17 项、文本审计 23 项通过。尚未更新本机安装副本或进行本版本真实 ZCode 界面切模验收。 + +## 0.4.1 — 2026-10-26 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **成员模型自动跟随修复轮**(0.4.0 验收发现的 5 个问题全部关闭;无契约/工具面变更,模型可见工具仍 9 个): + - **一致性判断改以宿主实际状态为准**:每轮同步前比对的是成员会话在宿主库中的实际选择(`session_entry` 选模条目 → `main_turn` 实际调用),`origin.modelSelection` 降为辅助记录——setModel 成功后、origin 更新前崩溃的恢复盘面不再凭 origin 相同就放行;实际状态无法确认时重新应用 Lead 选择;仅思考强度变化同样识别并同步;首轮已由 createChild 定模的不重复应用(零冗余 setModel)。 + - **失败可见性与重试控制**:解析失败与宿主应用失败统一落 `model-failed.json`(新增 `kind`/`attempts`/`nextAttemptAt`/`leadSignature`/`messageIds` 字段;不重建 pending 队列)。确定性拒绝(官方套餐/目录外/宿主明确不支持)暂停相同选择的自动重试;临时故障(超时/进程/app-server 未就绪)按 5s/15s/30s 退避、最多自动重试 3 次;Lead 换模或用户再次明确发送新消息即解锁。后台补投失败经宿主装配的通知钩子立即刷新成员展示(不等下一次轮次边界);消息持久保留、不误标 delivered。修复前同一条消息 6 秒内会重复 4 次 setModel 尝试,现在只尝试 1 次。 + - **创建前校验移到成员登记之前**:新增 provider `preflightMemberModel()`,roster 在写入 provisioning 事件前调用——Lead 用官方套餐/无可确认模型/已删除 Provider 时,spawn 请求明确失败且**不增加成员数量、不占用成员名、不创建隐藏子会话**;修正 Lead 模型后原名可重用。供给阶段复检保留(处理预检后配置漂移);真实供给失败仍是原 failed 成员语义。 + - **旧失败提示按验证成功清除**:宿主实际状态确认「成员与 Lead 已一致」时(无需额外 setModel)即清除旧失败记录与成员行诊断;仅 Lead 改了配置而未恢复成功时提示保留。 + - 既有 [v6 脚本](../zcode-agent-team-plan/stage-8-model-config/e2e-real-model-041.mjs)与[结果报告](../zcode-agent-team-plan/stage-8-model-config/e2e-real-model-041-evidence.json)记录六场景 ALL_PASS(创建继承 / 提交快照注入后跟随 / 选模条目注入后跟随 / daemon 重启恢复团队 / 套餐阻止+抑制 / 切回恢复交付恰一次)。这是**真实模型调用集成验收,切模事件由测试脚本注入,不包含真实输入框或 `/model` UI 交互**;宿主实际调用、会话选择和成员落库记录用于核验运行结果,不代表桌面切模交互已通过验收。两份材料位于本仓库之外。 +- 测试 787 → **840**(72 文件;两轮稳定);覆盖率 branches 83.25% → **85.12%**(达 85% 门槛;0.4.0 时点为既有技术债),statements/functions/lines ≥90% 保持;视觉基线 76 页零漂移;伴生面板交互 17 项全过。 + +## 0.4.0 — 2026-10-25 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **破坏性变更:成员模型全部收敛为「自动跟随 Lead」一条路线**。没有单独的成员模型配置——以下通道整体注销: + - 面板成员卡右上角**齿轮 + 模型设置弹窗**(含 `team_panel_call` 的 `modelOptions`/`setMemberModel` 两个动作)删除;面板恢复**零变更只读通道**口径(任务板/成员/详情不变)。 + - 对话工具 **`member_set_model` 删除**(模型可见工具 10 → 9;`interrupt:false` 时 8)。 + - `spawn_teammate` 的 **`model` / `thoughtLevel` 参数删除**;MCP 资源 **`team://models` 下线**(模型目录仅 provider 层内部分类使用,白名单脱敏纪律不变)。 +- **继承机制重做(三源判定 + 每轮执行前同步)**: + - Lead「最新已确认模型」= 三路按时间戳取最新:① 真实用户**提交消息时**宿主写入的模型快照(输入框切换在提交瞬间生效——修正对宿主 issue #7「条目不随输入框切换刷新」的依赖);② 会话选模记录(`/model` 命令刷新);③ 主轮实际模型调用(`query_source='main_turn'` 严格过滤,compact/标题生成/subagent/workflow 等辅助行绝不会被当成 Lead 模型)。旧「条目优先、usage 兜底」固定优先级删除。 + - 同步点 = 成员**每次开始执行前**(`launchTurn` 统一入口,首轮/消息唤醒/恢复团队三路共用):与成员实际生效选择比对,**有变化才应用**(零变化零开销);运行中的成员本轮跑完后在下一轮开始时同步(不打断已有工作);急需切换用现有中断能力结束当前轮次再续跑。 + - **失败绝不静默**:官方 coding plan 套餐(`account:*`/`builtin:*`)、Provider 已删/禁用、解析不出、setModel 被拒——一律**显式报错**(创建失败不落成员;续跑则阻止该轮启动),不再回退宿主缺省冒充继承成功,也不会把旧第三方模型显示为「同步成功」。成员卡保留一行继承失败诊断兜底。 + - 无后台监听、无新配置文件、无模型配置表;`model-pending.json` 队列机器删除。 + - 保留:空目录守卫(目录不可读 = 无法分类 → 照旧尝试、宿主终审)、档位缺省链(defaultVariant → max)、origin 只记实际生效者(`modelSource` 恒 `inherited`;`explicit` 仅历史数据兼容读取)。 +- **README/使用手册新增硬性边界声明**:不支持直接继承 GLM 等官方 coding plan 模型配置——成员模型必须来自你在 ZCode 设置中自配的第三方 Provider;Lead 使用套餐模型时团队创建/续跑会报错并指引切换。 +- 测试 878 → **787**(成员独立配置通道的 ~90 例随功能注销;继承/同步按新语义重写:三源各路取胜/陈旧条目跟提交/`/model` 跟条目/辅助行过滤/三种不可继承抛错/空目录守卫/每轮同步成功与阻止/套餐切换阻止/legacy 不应用;视觉基线 80 → 76 页,settings 4 张随弹窗下线,全页面反向断言「无齿轮/无弹窗/零凭据输入」)。 +- 文档回写:traceability §18 历史台账保留并标注注销关系,新增 §19(F39 收敛登记);架构说明数据流/降级表/模块地图同步 0.4.0 口径。 + +## 0.3.2 — 2026-10-25 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **第三方模型继承精化(分类优先绕过官方套餐)**: + - spawn 默认继承只覆盖**模型目录(Provider 注册表)内**的自配第三方模型;Lead 使用官方 coding plan 套餐(`account:*` / `builtin:*` Provider)时**零 setModel 尝试**直接回退宿主缺省,不再产生必败 RPC 与失败日志噪音。 + - 继承链按目录过滤 `session_entry` → `model_usage`(空目录守卫:目录不可读时不过滤,照旧由宿主终审);新导出 `catalogSupports(catalog, selection)` 作为唯一分类判据。 + - 跳过仍写 `model-failed.json`(防可见性回归),诊断区分两态:官方套餐 →「Lead 当前使用官方套餐模型(provider/model),成员无法继承,已回退宿主缺省;可在 spawn 时指定自配模型或改用第三方模型」;其他目录外模型 →「Lead 模型 provider/model 不在可用目录,已回退宿主缺省」。 + - 显式指定通道与「尝试后失败」路径一字未动(无契约/工具面变更,backend/面板零改动);origin 仍只记实际生效者。 + - README §2.1 与使用手册补继承边界声明。 +- **取消「简洁/详细」双模式**:成员会话查看视图固定为按轮摘要一种形态。 + - 每轮显示**用户指令 + 动作组 + 每轮结论**:动作组(`toolGroup`)一行汇总本轮全部工具,点击就地展开逐条工具(名称/状态/载荷);本轮最后一条非空 assistant 文本作为该轮结论。 + - **全量转录不进视图**:需要原始记录时走 `team-ctl`/事件日志/宿主会话库。 + - 计数显示「n 条 · 共 sourceTotal 条转录」(`sourceTotal` = 投影前原始条数)。 + - **mode 参数与切换按钮全部移除**:`team_panel_call` 的 detail 请求/响应均无 `mode`,面板与伴生页无模式切换按钮;CLI 删 `--mode`(`team-ctl transcript ` 即摘要形态)。 + - 契约写实保留:`items.kind` 为 `"text"|"toolCall"|"toolGroup"`;`kind:"toolResult"` 从未独立实现,工具结果并入 `toolCall` 载荷。 + - README / 使用手册 / 架构说明 / 运维手册 / 测试手册 / 命令文档 / 追溯矩阵同步改写为单一摘要口径。 +- 测试 875 → **878**(本机 env 净化实测两轮稳定,75 文件;分类五态 + `catalogSupports` 新增)。 +- 视觉基线 **80 页不变**(无 UI 变更)。 +- 模型可见工具面与成员/任务行为不变(仍 10 工具,`interrupt:false` 时 9)。 + +## 0.3.1 — 2026-10-25 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **修复 GitHub #6:模型/思考强度设置失败全程无提示**(单次尝试语义,全链路可见): + - `member_set_model` 失败不再包装成"下一轮生效":空闲成员立即应用失败直接返回 `applied:"failed"` 与宿主原因原文(如"Provider Registry 中不存在 Model"),不落 pending——消灭"每轮静默重试每轮失败"的无限循环。 + - 失败落 `model-failed.json` 并在三个面立即可见:`list_agents` 成员行 diagnostics(对话通道)、面板成员卡诊断行、模型弹窗"上次设置未生效:…(原因)"错误色提示;成员列表模型名保持真实值,不再维持"快成功"观感。 + - 运行中成员的"下一轮生效"若应用失败 = 终态(删 pending + 记失败 + 继续旧模型跑轮)。 + - spawn 继承降级(Lead 模型不可用于成员,如订阅套餐型)同样落诊断——#5 的可见性半边(能力仍待宿主开放)。 + - 任一次成功应用清除失败记录;`02 规格 §9.13` 描述补失败语义(F01 双源同步)。 +- 测试 864 → 875;真模型 E2E 十一步 ALL_PASS(含失败路径三面可见性)。 + +## 0.3.0 — 2026-10-25 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **成员会话查看视图新增「简洁/详细」双模式**(detail 契约〔视图修订 2026-10-25〕): + - 默认**简洁**(`mode:"summary"`):按轮投影为「用户指令 + 每轮动作组 + 每轮最终结论」;动作组(`toolGroup`)一行汇总,点击就地展开逐条工具(名称/状态/载荷)。 + - **详细**(`mode:"full"`):修订前的全量转录流,供审计与排障;行为逐字不变。 + - `team_panel_call` 的 detail 请求新增 `mode`(缺省 `summary`);响应回显 `mode` 并新增 `sourceTotal`(投影前原始条数);`items.kind` 增 `toolGroup`(`count` + `tools[]`)。 + - **契约写实**:`kind:"toolResult"` 从未独立实现——工具结果并入 `toolCall` 载荷;本次只改文档口径,不新增类型、不改数据源。 + - **跨模式 `seq`/`cursor` 不通用**:切换模式重置到末页(面板/伴生页);CLI 每次调用独立。 + - CLI 对等:`team-ctl transcript --mode summary|full`(缺省 summary,与面板共用同一合成函数)。 + - 面板与伴生页新增模式切换按钮;README / 使用手册 / 架构说明 / 运维手册 / 命令文档 / 追溯矩阵同步更新。 +- 测试 836 → **864 passed**(`test/panel/detail.test.ts` 16 → 26;`test/ui-core/detail-render.test.ts` 17 → 28)。 +- 视觉基线 76 → **80 页**(新增 detail-summary × light/dark × zh/en 共 4 页)。 +- 模型可见工具面与成员/任务行为不变(仍 10 工具,`interrupt:false` 时 9)。 +- 遗留登记(GitHub issue 跟踪):详情文本 markdown/代码块排版未实现(当前纯文本);`toolResult` 契约偏差已写实;U03 盲测仍未执行;模式选择不跨面板重开保持。 + +## 0.2.0 — 2026-10-25 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- **teammate 模型可配置化**(F33–F36,02 规格 §9.13/§10 修订): + - spawn 默认**继承 Lead 的模型与思考强度**(Lead 会话 `runtime/model_selection` 权威条目 → `model_usage` 兜底;条目不可用时兜底重试一次,origin 只记实际生效者)。 + - `spawn_teammate` 新增可选参数 `model`(`"providerId$modelId"` 或裸 modelId,经 `team://models` 目录消歧)与 `thoughtLevel`。 + - 新增第 10 个工具 **`member_set_model`**:mid-life 修改成员模型/思考强度;空闲成员立即生效,运行中成员下一轮生效(pending 标记 + 下轮兜底)。 + - 新增只读资源 **`team://models`**:模型目录(运行时注册表 `provider_config.json` 白名单投影,含 config.json 回退;**绝不输出 apiKey/baseURL**)。 + - 面板成员卡右上角**齿轮 → 模型设置弹窗**:provider/模型/思考强度三级联动、当前生效值与来源标识(继承自 Lead / spawn 指定 / 手动修改 / CLI 缺省)、高级模式引导(ZCode 设置加 provider 后刷新;弹窗零凭据输入)。`team_panel_call` 新增 `modelOptions`/`setMemberModel` 两动作——面板通道首个(且唯一)受控变更动作,任务板仍零变更。 + - 生效机制:会话库 `session_entry(runtime/model_selection)`(`session/setModel`,`persistAsWorkspaceLastUsed:false`),headless `--resume` 每轮自动恢复;一次设置全轮次生效。 +- 测试 697 → 836;视觉基线 72 → 76(重录 28 + 新增 settings 弹窗 4)。 + +## 0.1.3 — 2026-10-24 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- 写域重叠警告仅挂双方 `in_progress` 的任务对(成对对称):主体为 `completed`/`pending` 时不再产生警告。 +- 面板 advisory 警告色由错误红降为警告黄(新增语义令牌 `--at-warning-text`);红色仅保留给真报错。 +- **无 MCP 契约/schema 变化**:工具清单、入参/出参与 TASK_VIEW 字段不变,仅派生口径与颜色变化。 + +## 0.1.2 — 2026-10-24 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- 文档定稿版:README 补齐安装/启用/快速上手/工具速查/配置/Node 自检/卸载数据处置/故障排查/宿主基线/限制与偏差(D1–D27)。 +- 新增《使用手册》(含桌面 MCP Apps 面板、::visualize 卡片、CLI 文本摘要与静态卡片实拍截图),并随包分发(`docs/使用手册.md` 与 `docs/assets/manual/`)。 +- 仓库新增内部移交文档:架构说明(as-built)、运维手册、测试手册(不随包分发)。 +- **无运行时行为变更**:与 0.1.1 相比仅文档与包内文档资源变化;阶段二的 0.1.0→0.1.1 升级演练证据继续有效。 + +## 0.1.1 — 2026-10-24 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- 升级演练版本:功能与 0.1.0 相同,仅版本号与发布元数据变化,用于验证 0.1.0 → 0.1.1 的升级路径。 + +## 0.1.0 — 2026-10-24 + +描述:智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。 + +- 首个发布包:stage-1–6 交付内容(域核心、工具面、队友运行时、MCP Apps 面板、成员会话隔离)打包为可安装插件。 +- 随包提供 `LICENSE`(MIT)与 `THIRD-PARTY-NOTICES.md`(bundle 内联依赖的许可声明)。 +- 构建基线:Node ≥ 22;宿主实测基线 Desktop 3.16.2 / CLI 0.17.0。 diff --git a/external_plugins/agent-team/LICENSE b/external_plugins/agent-team/LICENSE new file mode 100644 index 00000000..e69e55dd --- /dev/null +++ b/external_plugins/agent-team/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 agent-team-poc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/external_plugins/agent-team/README.md b/external_plugins/agent-team/README.md new file mode 100644 index 00000000..98f8a76a --- /dev/null +++ b/external_plugins/agent-team/README.md @@ -0,0 +1,295 @@ +# Agent Teams + +[中文](./README_CN.md) + +Bring "Lead + multiple teammates" collaboration into ZCode: the Lead spawns teammates inside a conversation, shares a task board, exchanges messages, and watches live team status in an MCP Apps panel. + +- Best for: parallel work you want to split up, handing implementation/review/testing to different members, or delegating a multi-step job to a reusable crew. +- Roles: Lead = the current conversation (the agent you are talking to); teammates = independent child sessions created by the plugin, sharing the Lead's working directory. +- Surfaces: Desktop = the "Agent Team" MCP Apps panel (live); CLI = the `/team` text summary + the `team-ctl` tool (can also render static cards). + +> Host baseline: finalized on **ZCode Desktop 3.16.2 / CLI 0.17.0** (measured, not guessed); the release drill was re-verified on Desktop 3.16.3 / CLI 0.17.0, and the desktop entry paths on Desktop 3.17.1. Lower versions are unverified and unsupported. + +## Install + +### Desktop (Plugin Marketplace UI) + +1. Open **Plugin Marketplace** and find **Agent Teams** (category: developer tools). +2. Click **Install**. Afterwards you can confirm and toggle it under **Settings → Plugins**. + +### CLI + +```bash +zcode plugins install agent-team@zcode-plugins-official +zcode plugins enable agent-team@zcode-plugins-official +``` + +## Enable + +- Enabled by default after install; the switch and its configuration live in **Settings → Plugins**. +- The declared SessionStart / Stop / UserPromptSubmit hooks take effect **as soon as the plugin is enabled** — no trust grant or hooks toggle is needed (verified in a clean environment). +- In the desktop default permission mode, the first agent-team MCP tool call prompts for permission; choose "Allow once" or "Always allow for this project". This is the host's tool permission and unrelated to hooks. + +## Using it in a conversation + +**Panel entry:** click **"+"** on the right of an existing conversation: +- Universal path (verified on official ZCode 3.17.1): **"All plugins" → "Personal" → "Agent Team" → "Open"**. +- When the host provides an "Agent Team" item in "New tab" (official 3.17.1 does not yet include it; requires a host build with this entry): **"New tab" → "Agent Team" → "Open"** — no need to enter the plugin list. + +After install and enable you need **no special command**: the teamwork policy is injected into the conversation context automatically by the SessionStart hook (D10). Just start a new task and describe your goal. There are three invocation surfaces: + +| Surface | How to trigger | What it does | +|---|---|---| +| Natural language (main channel) | Just state a goal / give orders | Everything: spawning teammates, assigning tasks, messaging; the policy is auto-injected and the model knows which team tools to use | +| `/team` | Type `/team` | Prints a text summary of team status + panel/command entries (**read-only when called without arguments**, creates/modifies nothing) | +| `/team ` | e.g. `/team expand this story into three characters` | **Actually runs the task with the team**: prints the status summary, then spawns teammates, assigns work, waits and summarizes (if the model cannot be inherited it says so and does the work directly) | +| `/team-coordination` | Type `/team-coordination` (full name `agent-team:team-coordination`) | Manually (re)load the teamwork policy skill; use when a very long session has lost it | + +### 1. Just state the goal (default `auto`: on-demand delegation) + +Start a **new task** (old tasks do not refresh plugin capabilities) and describe the goal. Since 0.5.0 the default `leadMode: auto` follows on-demand delegation semantics: with no team spawned yet, the session behaves like a plain single agent — questions, small single-file changes and read-only summaries are handled directly; for goals that clearly benefit from multiple roles in parallel, disjoint write scopes, or long tasks needing their own context, the Lead forms a team: + +```text +Push two things in parallel: one teammate adds unit tests for src/utils, another reviews the wording of README and CHANGELOG, then summarize. +``` + +Once a team exists in the session (durable — inactive/failed members count), the Lead judges each request by delegation value: delegate work that is worth the team workflow — tasks with acceptance criteria, owners and independent verification (D26/D27) — and handle the rest directly with a one-line reason (issue #9 / D28). + +### 2. Precise control and the other two modes + +At any time you can give explicit orders: + +```text +Create a teammate named reviewer, have it check the first three paragraphs of README for typos, then summarize its findings. +``` + +```text +Send reviewer a message: focus on mixed Chinese/English punctuation. +``` + +```text +List the current members and task statuses. +``` + +Two more modes: `always` restores the pre-0.5.0 proactive orchestration from the very first message (decompose, staff up, assign, verify — no step-by-step steering needed); `off` disables Agent Teams entirely (no team context injected, no team tools registered). + +The model maps these phrasings to the right tools (`spawn_teammate` / `send_message` / `list_agents` / `team_task_list` …); you never need to remember tool names. + +### 2.1 Model and reasoning effort (auto-follows the Lead, nothing to configure) + +**Since 0.4.0 there is exactly one path for member models: automatically follow the Lead's latest confirmed model and reasoning effort.** There is no per-member model configuration — no gear popup in the panel, no `model` parameter on `spawn_teammate`, and no "switch this member's model" instruction. You only manage the Lead's model; members sync before every turn. + +```text +Create a teammate named reviewer to check the first three paragraphs of README for typos. +``` + +- **When it syncs**: before each execution (first turn, wake-up by a new message, team resume) the member compares against the Lead's latest confirmed choice (resolved from the host's actual session state, 0.4.1); applied only on change, zero overhead otherwise. A running member syncs at its next turn start (never interrupted mid-turn); interrupt it first if you need an immediate switch. +- **What "confirmed" means**: the model **at the moment you actually submit a message** (the host snapshots it when saving), cross-checked against the `/model` selection record and the main-turn call history — newest of the three wins. Merely toggling the dropdown without submitting is not guaranteed to sync. +- **Failures are never silent; retries are bounded (0.4.1)**: when the Lead's model cannot be inherited (official coding plan, deleted/disabled Provider, unparseable state), spawning/resuming fails loudly with the reason — it never silently runs a different model. The failure shows in the member's diagnostics and pending messages are preserved. Deterministic rejections (plan/out-of-catalog) suspend auto-retry; transient faults (timeouts) back off 5s/15s/30s, at most 3 auto-retries. Switching the Lead back to a usable model — or sending a new message — resumes delivery and clears the stale error. +- **Pre-spawn validation (0.4.1)**: when the Lead's model is not inheritable, `spawn_teammate` fails **before** registering the member — no failed member, no name consumed; after fixing the Lead's model the same name is reusable. +- **Official coding plans cannot be inherited (hard boundary)**: members are independent CLI processes and the host does not hand subscription-plan credentials (`account:*` / `builtin:*` providers, e.g. GLM official coding plans) to them, so **inheriting an official coding-plan model is not supported**. Spawning/resuming while the Lead uses a plan model fails; switch the Lead to your own third-party model first (ZCode Settings → Model Services, add your own Provider + API key). +- **Solo fallback when teammates are unavailable (0.5.1; timing refined in 0.5.2)**: when the Lead's confirmed model is an official plan model, the Lead is told once per session that teammates cannot be spawned — it then does all the work itself instead of wasting turns on failing spawns. Since 0.5.2 the decision is taken from the model the host reports at session start, so even a brand-new session knows before your first message (older hosts fall back to the first prompt). The note self-corrects: if you switch the Lead to a third-party model — before the first message or mid-session — the next prompt carries a one-time update that teammates are available again, and a successful spawn always restores normal team use. + +### 3. `/team` for status + +Type `/team` any time: the first line reads "Members N · Shared tasks T", followed by one line per member and task (same wording as the panel dictionary), plus panel/command entries depending on the runtime. Refresh semantics: the desktop MCP Apps panel is live (subscription push, no manual refresh); on CLI every `/team` run is fresh. + +**With an argument it also does the work**: `/team ` prints the summary and then actually builds the team — spawns members by role, creates shared tasks with write scopes when coordination is needed, waits for results and summarizes. Without arguments it stays strictly read-only. + +### 4. `/team-coordination` to reload the policy + +The main channel is the automatic hook injection, so manual loading is rarely needed. Two cases: + +- In very long sessions the injected policy may be compacted away (D24): type `/team-coordination` (or ask the model to "reload the teamwork policy skill") to restore it; +- Or load it on demand when you want the session to follow team discipline. + +### What a successful run looks like + +Using "create reviewer to check README typos" as the example: + +1. The "Agent Team" panel appears in the conversation (the `spawn_teammate` result carries a panel-open hint and the desktop opens it), showing `lead` (current session) and `reviewer`; +2. `reviewer` starts working; tasks and statuses change on the panel/board; +3. `reviewer` reports back; the Lead (after independent verification, when it delegated the work) summarizes for you; +4. `reviewer`'s session is a hidden child session — it never appears next to the Lead in the left task list. + +## Tool reference (9 model-visible tools; 8 with `interrupt:false`; 0 with `leadMode:off`) + +| Tool | Who uses it | Purpose | +|---|---|---| +| `spawn_teammate` | Lead | Create a named persistent teammate (`context: fresh\|fork`; model auto-follows the Lead, no separate parameter; staff up when the goal clearly benefits from delegation) | +| `send_message` | Everyone | Message another member: delivered at the nearest turn boundary while running; wakes/resumes an idle member | +| `list_agents` | Everyone | List Lead + all teammates with targets and availability (`inactive` = no turn running, not a failure) | +| `interrupt_agent` | Lead | Interrupt a teammate's current turn, preserving its pending inbox (**not registered when disabled → 8 tools**) | +| `wait_agent` | Everyone | Return pending Lead inbox messages first; otherwise wait for Team changes. No peer progress returns noProgress; timeout returns timedOut. Never wakes members. | +| `team_task_create` | Everyone | Create an unassigned task on the shared board (optional `blocked_by` / `write_scopes`) | +| `team_task_list` | Everyone | List tasks: status, owner, revision, blocking, write-scope warnings (paginated/filterable) | +| `team_task_get` | Everyone | Read one task's latest full content (must-read before editing) | +| `team_task_update` | Everyone | CAS task actions via `expected_revision`: claim / release / edit / set_dependencies / complete / reopen / reassign / delete | + +There is also an app-only loopback tool `team_panel_call` (panel heartbeat/refresh/detail with **per-turn summaries**; **read-only channel, zero mutation capability**, not model-visible); the diagnostic probe `team_ping` is exposed only with `TEAM_DEBUG_TOOLS=1`. + +## Configuration (userConfig) + +Edit under **Settings → Plugins → Agent Team**; changes apply to new tasks (running sessions keep the config they started with). + +| Option | Default | Description | +|---|---|---| +| `maxMembers` | 8 | Max teammates per team (Lead excluded, failed included) | +| `maxTasks` | 256 | Max tasks on the board | +| `maxMessageBytes` | 65536 | Max bytes per member-to-member message | +| `disposalTimeoutMs` | 5000 | Timeout for team disposal (settlement and reclaim) | +| `interrupt` | true | When off, the model gets 8 tools (`interrupt_agent` is not registered) | +| `leadMode` | auto | `auto`: on-demand delegation (plain single agent until a team exists, then judge by delegation value); `always`: always orchestrate proactively; `off`: disable Agent Teams entirely (no injection, 0 team tools). Legacy values `orchestrator`/`collaborator` are treated as `auto` (issue #9) | + +## Network access, dependencies and side effects + +| Item | Declaration | +|---|---| +| Network access | **No outbound requests.** The daemon talks to the host over stdio; the teammate ↔ host app-server bridge uses local inter-process channels; the optional companion page (`TEAM_COMPANION=1`) listens on loopback `127.0.0.1` only. Model requests are made by the host using the Providers you configure — unrelated to this plugin | +| Model/API dependencies | Members are driven by the host-bundled `zcode` CLI and follow the Lead's current model every turn (see 2.1); **official coding plans cannot be inherited** (plan credentials are not forwarded); the plugin itself needs no API key | +| File writes | Only the plugin data directory `$ZCODE_PLUGIN_DATA` (`teams/`, `logs/`, `meta/`, checkpoints) plus two whitelisted points in the host task index (member-session hiding anchor, `sidebar-audit --apply`, see D25); the host `db.sqlite` is strictly read-only | +| Command execution | Hooks, the daemon and `team-ctl` are the plugin's own Node scripts (`runtime/*.mjs`) run by the host's Node; teammates are host CLI child processes; the plugin never runs arbitrary shell commands | +| Hooks | SessionStart / Stop / UserPromptSubmit (`hooks/hooks.json`, effective on enable) | +| MCP servers | `team-daemon` (stdio) | +| Third-party code | Inlined MCP SDK and other third-party software with licenses: [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md) | + +## CLI usage + +```bash +# /team command: prints the team status text summary (desktop & CLI) +/team + +# With an argument: runs the task with the team (spawn + assign + summarize) +/team expand this story into three characters + +# Direct disk replay (same source as /team) +node /runtime/team-ctl.mjs state # text summary +node /runtime/team-ctl.mjs state --json # machine-readable +node /runtime/team-ctl.mjs transcript # per-turn member summary +node /runtime/team-ctl.mjs widget --standalone --out /tmp/team.html --theme dark --lang en +node /runtime/team-ctl.mjs tail # follow the event log +``` + +`` = `$ZCODE_PLUGIN_DATA/teams/` (on CLI usually `~/.zcode/cli/plugins/data/agent-team@/teams/…`). + +## Node requirement + +The daemon, hooks and `team-ctl` all run on Node and require **Node ≥ 22**. Check before installing: + +```bash +node -v +``` + +Expect `v22.x` or higher. Below v22 the daemon startup self-check warns and the panel/tools may be unavailable; the actual version is written to `$ZCODE_PLUGIN_DATA/logs/daemon-lifecycle.jsonl` (fields `node`, `nodeWarn`). + +## Uninstalling and your data + +**Back up first, then uninstall.** The default uninstall deletes team data irreversibly. + +```bash +# 1) Locate the plugin data dir (dataPath at install time; also visible in plugins list --json) +DATA="$HOME/.zcode/cli/plugins/data/agent-team@" +# 2) Back up (keeps the task board, members, messages, event log) +tar -czf ~/agent-team-backup-$(date +%Y%m%d).tar.gz -C "$(dirname "$DATA")" "$(basename "$DATA")" +``` + +Measured behavior (2026-10-24 clean-environment drill): + +| Entry | Default uninstall | Can data be kept? | +|---|---|---| +| CLI | `zcode plugins uninstall agent-team@` **deletes the entire plugin data directory** (board, members, messages); the current version cache is removed, older version caches and the marketplace registration stay | Yes: `--keep-data` keeps the data directory (event-log hash unchanged) and only removes code + enablement; non-interactive shells need `--force` | +| Desktop | Settings → Plugins → more actions → Uninstall; the confirm dialog states cache, data and config deletion; measured: **deletes the data directory contents** (empty dir remains), current version cache removed | **No** UI equivalent | + +Note: task windows still open at uninstall time may later **recreate an empty data skeleton** at the old path (0-byte `events.jsonl`); the original team data does not come back — do not mistake the reappearing directory for "data is still there". Close the related task windows after uninstalling. + +## Troubleshooting + +### 1. First check whether the plugin exists and is enabled + +```bash +zcode plugins list | grep agent-team +zcode plugins list --json # version / rootPath / dataPath / diagnostics +``` + +Desktop: confirm the "Agent Team" toggle in **Settings → Plugins**; its three hooks show under **Settings → Hooks**. + +### 2. Log locations (all under the plugin data directory) + +| File | Contents | +|---|---| +| `logs/hooks.jsonl` | Full env overlay and input digest per SessionStart / Stop / UserPromptSubmit — **check here to see whether hooks ran** | +| `logs/daemon-lifecycle.jsonl` | Daemon start/reclaim: pid, node version, data dir, `nodeWarn`, SIGINT handling | +| `logs/provider.jsonl` | Teammate turns and delivery details (debugging) | +| `logs/requests.jsonl`, `logs/meta-log.jsonl` | Tool calls and panel loopback records | +| `meta/runtime-config.json` | Effective config persisted by the daemon (hooks read the same file) | +| `teams//events.jsonl` | Team event log (append-only; `team-ctl tail` follows it) | +| `teams//coordinator.audit.jsonl` | Coordinator lock acquire/release/takeover audit | + +### 3. How to investigate hooks not taking effect + +1. Confirm the plugin is enabled (hooks do not run while disabled); +2. Open a **new conversation**, then check whether `logs/hooks.jsonl` gained a `sessionstart` record; +3. No record → check **Settings → Hooks** lists the three agent-team hooks (SessionStart / Stop / UserPromptSubmit) and whether the plugin carries `diagnostics` (version/manifest issues); +4. Record exists but the model ignores team policy → check the record's `env_overlay.ZCODE_PLUGIN_ROOT` points at the current install; after upgrades old sessions keep the old version — start a new conversation. + +### 4. Common symptoms + +| Symptom | Cause and handling | +|---|---| +| `Duplicate plugin hooks file ignored: hooks/hooks.json` in `plugins list` after install | Known warning: the manifest hooks declaration duplicates the host's auto-discovery of the same path; the host ignores it explicitly. All three hooks still run. Cleanup planned for a later version | +| Teammate stuck `provisioning` / cannot be created | Check `logs/provider.jsonl` and `logs/daemon-lifecycle.jsonl`; confirm the `zcode` executable is discoverable (`TEAM_ZCODE_BIN` overrides) and member quota `maxMembers` is not exceeded | +| "Member cannot inherit the Lead model" on spawn/resume | Expected (0.4.0): the only path is following the Lead; when the Lead is on an **official coding plan** (`account:*`/`builtin:*`) or the Provider is deleted/disabled it fails loudly, never silently switching models. Fix: switch the Lead to your own third-party model (ZCode Settings → Model Services) and retry. 0.4.1: spawn pre-checks before registering (no name consumed); the same failure does not retry forever (deterministic rejections suspend; transient faults back off 5s/15s/30s ×3); switching the Lead back or sending a new message resumes delivery and clears the error | +| Desktop tool calls hang or `Client closed` | Known host limitation (D11): desktop callTool does not rebuild the connection after the daemon is idle-reclaimed. Start a new task and call immediately to hit a live daemon; the panel heartbeat keeps it alive as long as possible | +| Panel numbers frozen | The panel refreshes via subscription + heartbeat; cross-check with `/team` or `team-ctl state`. Static cards/views do not probe liveness and are conservative | +| No change after upgrading | The host pins a plugin runtime per conversation: start a new task after upgrading; the CLI's "Restart zcode to apply" hint is the same | +| Old team sessions appear in the left task list | Leftover data: `node runtime/team-ctl.mjs sidebar-audit --apply` archives them (dry-run by default, reviewable) | +| Persisted team record corrupt | Reports `persisted Agent Teams … payload is invalid`. Back up `teams//` first, then re-check with `team-ctl state`; never hand-edit `events.jsonl` (breaks seq continuity) | + +### 5. Safely wiping the data directory + +Once you no longer need historical teams you may delete `$ZCODE_PLUGIN_DATA` entirely (same data disposal as the default uninstall). **Back up first**; the board and messages cannot be recovered afterwards. + +## Limitations and deviations (user-readable, D1–D27) + +This plugin is a re-implementation of DSH Agent Teams on ZCode. The deviations below are **registered and acceptance-tested** adaptations from the gap analysis ledger D1–D27 (numbering per that ledger). + +| ID | What you will observe | +|---|---| +| D1 | Team events live in the plugin's own data directory (JSONL), not the Lead's session log; session export/rollback excludes team events | +| D2 | "Interrupting a running member" is delivered at the next turn boundary (the host has no steer primitive); messages queue while the target runs — never dropped or duplicated | +| D3 | `context:"fork"` falls back to "fresh + Lead's completed-turn transcript (truncated)" when a true fork is impossible; not KV-prefix sharing | +| D4 | The main UI is the in-conversation MCP Apps panel; no upstream hover button/popover/pin; the `::visualize` snapshot card is desktop-only | +| D5 | Member sessions stay out of the left task list by default; the panel offers a read-only member conversation view. Legacy visible rows can be archived with `sidebar-audit` | +| D6 | The Lead still sees the host's built-in Task tools (cannot be disabled); teammates have Task disabled and team tools are policy-preferred | +| D7 | One sentence about "file version conflicts" in the policy text is replaced with ZCode file-tool semantics; everything else is verbatim | +| D8 | The coordinator is ephemeral: the daemon is reclaimed by the host when idle and any instance can take over; a momentary `TEAM_DISPOSED` error may appear during handover — just retry (measured takeover ≤5s for a truly dead coordinator; a stalled-but-alive holder is detected via PID liveness and given a bounded grace instead of being stolen from) | +| D9 | No SessionEnd hook: disposal is best-effort at daemon exit plus reconciliation on next start; under very short grace only a reconcilable state may remain | +| D10 | The policy is injected into message context by the SessionStart hook, not the system prompt; injected text does not land in the transcript; disabling hooks triggers a fail-loud warning | +| D11 | Desktop callTool may hang / `Client closed` after daemon reclaim without recovering in that session; a new task recovers. Teammates use separate processes and are unaffected | +| D13 | Tool entries declare no `outputSchema` (host limitation); output contracts are pinned by tests | +| D14 | With missing identity, error messages use an `` placeholder | +| D15 | Argument type errors return `TEAM_INVALID_ARGUMENT` with `param "" must be …`; these are tool-face messages within the existing 27-code set | +| D16 | When two daemons serve one team (proxy mode): `list_agents` may conservatively show active members as `inactive`; `wait_agent` uses the coordinator to receive messages and assess noProgress | +| D17 | Idle reclaim does **not** terminate teammate turns by default (keep-asleep); set `TEAM_DRAIN_ON_DISPOSE=kill` to drain fully | +| D18 | "Delivered" to the Lead means the hook injection receipt (the host has no direct injection primitive; injection is not in the transcript); externally it is still `{sent:true}` | +| D19 | Hooks read the config persisted by the daemon; before the first daemon start they use defaults (e.g. `interrupt=true`) | +| D20 | Waking an idle Lead is a gray feature: by default no new turn is started and messages stay pending; `TEAM_WAKE_LEAD=1` enables it | +| D21 | Static cards do not probe liveness: member status maps conservatively from phase (active→inactive, lead always inactive); only the live panel/companion shows running | +| D22 | The diagnostic tool `team_ping` is not in the model tool list by default (9 model-facing tools, 8 with `interrupt:false`); `TEAM_DEBUG_TOOLS=1` exposes it | +| D23 | Historical event names/old checkpoints auto-upgrade: legacy `team/message` normalizes to `team/message/queued`, old delivered structures to string arrays; historical teams stay readable | +| D24 | Policy text injects on SessionStart (startup/resume); in very long Lead sessions it may be lost to context compaction — reload the skill or start a new task | +| D25 | The plugin writes only two whitelisted points in the host task index (session-hiding anchor tombstone, `sidebar-audit --apply`); `db.sqlite` is strictly read-only | +| D26 | `always` mode (pre-0.5.0 default `orchestrator`): the Lead proactively staffs/assigns/accepts and does not implement itself (except one-line fixes or when nobody can take it) | +| D27 | Task `complete` means "submitted": the Lead must independently verify before acceptance; failures are `reopen`ed with concrete findings, passes append an acceptance note to the task | +| D28 | Since 0.5.0 the default is `auto` (issue #9): no mode section is injected before a team exists; after the first teammate the on-demand section applies (delegation-value judgment with positive/negative examples); `off` disables injection and team tools entirely; legacy `orchestrator`/`collaborator` values migrate to `auto`; a stale pre-0.5.0 runtime-config is treated as unset | +| D29 | When the Lead's confirmed model is an official plan model (issue #5), hooks inject a one-time solo note (do all work yourself, don't call spawn_teammate; non-permanent — a later successful spawn restores normal team use) and the spawn error message offers the same fallback; detection is optimistic (unknown/failed reads never trigger the note) | +| D30 | 0.5.2: the solo note is decided first from the `model` the host passes to the SessionStart hook (brand-new sessions know at startup; the db three-source probe remains the fallback), and every later prompt reconciles it against the db — once the db confirms a non-plan model, a one-time retraction note restores normal team use | +| D31 | 0.5.2: the build runs `node --check` on every runtime bundle and rebuilds up to 3 times on failure; the release packer re-checks the staged and unpacked trees (guards against torn writes on slow/external volumes) | + +## Documentation + +- [User manual with screenshots (Chinese)](docs/使用手册.md) +- [Repo wiki: architecture, flows and source navigation (source repo only, not shipped)](docs/repo-wiki.md) +- Internal handover docs (source repo `docs/`, not shipped): `架构说明-as-built.md`, `运维手册.md`, `测试手册.md` +- [Changelog](CHANGELOG.md), [License](LICENSE), [Third-party notices](THIRD-PARTY-NOTICES.md) +- Source repository: diff --git a/external_plugins/agent-team/README_CN.md b/external_plugins/agent-team/README_CN.md new file mode 100644 index 00000000..2d3b93d2 --- /dev/null +++ b/external_plugins/agent-team/README_CN.md @@ -0,0 +1,295 @@ +# 智能体团队(Agent Teams) + +[English](./README.md) + +把「Lead + 多个 teammate」的协作方式带进 ZCode:Lead 在会话里创建队友、共享任务板、收发消息,并用 MCP Apps 面板实时看到团队状态。 + +- 适用:需要并行拆活、希望把实现/审查/测试分给不同成员,或想把一段多步工作交给可复用的成员协作。 +- 角色:Lead = 当前会话(你正在对话的 agent);teammate = 插件创建的独立子会话,与 Lead 共享同一工作目录。 +- 载体:桌面 = 「智能体团队」MCP Apps 面板(实时);CLI = `/team` 文本摘要 + `team-ctl` 工具(可生成静态卡片)。 + +> 宿主基线:本插件在 **ZCode Desktop 3.16.2 / CLI 0.17.0** 上完成终验(实测基线,非推测);发布演练另在 Desktop 3.16.3 / CLI 0.17.0 复测通过,桌面入口路径在 Desktop 3.17.1 复测通过。更低版本未验证,不在支持范围内。 + +## 安装 + +### 桌面(插件市场 UI) + +1. 打开 **插件市场 / Plugin Marketplace**,在市场中找到 **「智能体团队 / Agent Teams」**(分类:开发者工具)。 +2. 点 **安装 / Install**;安装后可在 **设置 → 插件 / Settings → Plugins** 中确认与启用。 + +### CLI + +```bash +zcode plugins install agent-team@zcode-plugins-official +zcode plugins enable agent-team@zcode-plugins-official +``` + +## 启用 + +- 安装后默认启用;在 **设置 → 插件** 里可查看开关与配置。 +- 插件声明的 SessionStart / Stop / UserPromptSubmit hooks **随启用直接生效**,不需要信任授予或 hooks 开关(已在干净环境实测)。 +- 桌面默认权限模式下,agent-team 的 MCP 工具首次调用会弹「需要权限」确认;选择「允许(仅本次)」或「始终允许本项目」即可。这是宿主的工具权限,与 hook 无关。 + +## 在会话中使用(怎么调用) + +**面板入口:** 在已有会话右侧点 **「+」**: +- 通用路径(官方 ZCode 3.17.1 实测):**「查看所有插件」→「个人」→「智能体团队」→「打开」**。 +- 宿主在「新标签页」中提供「智能体团队」入口时(官方 3.17.1 尚未提供,需含该入口的宿主版本):**「新标签页」→「智能体团队」→「打开」**,无需进入插件列表。 + +装好、启用后**不需要任何专门命令**:团队协作策略已由 SessionStart hook 自动注入会话上下文(D10),在新任务里直接对话即可。共有三个调用面,按需取用: + +| 调用面 | 怎么触发 | 干什么 | +|---|---|---| +| 自然语言对话(主通道) | 直接说目标 / 下指令 | 创建队友、分派任务、收发消息等全部操作;策略已自动注入,模型自己知道该用哪些团队工具 | +| `/team` | 会话里输入 `/team` | 输出团队状态摘要 + 面板/命令入口(**无参数时只读**,不创建/修改任何数据) | +| `/team <任务>` | 例如 `/team 把这段故事扩写成三个角色` | **用团队真的执行该任务**:先输出状态摘要,再建队、分派、等结果并汇总(模型不可继承时明确说明并改为直接完成) | +| `/team-coordination` | 输入 `/team-coordination`(全名 `agent-team:team-coordination`) | 手动(重新)加载团队协作策略 skill;长会话策略丢失后恢复用 | + +### 1. 直接说目标(默认 `auto`:按需委派) + +新建一个任务(**必须是新任务**——旧任务不会刷新插件能力),直接描述目标即可。0.5.0 起默认 `leadMode: auto` 为按需委派语义:会话还没建过队时就是普通单 agent——问答、单文件小改动、纯调研汇总直接处理,不为委派而委派;目标明显值得协作(多角色并行、写域互斥分人、长任务需要独立上下文)时 Lead 才组队: + +```text +帮我并行推进两件事:一边给 src/utils 补单元测试,一边审查 README 与 CHANGELOG 的措辞,完成后汇总。 +``` + +会话里建过队后(持久判定——inactive/failed 成员也算),Lead 按委派价值逐请求判断:值得走团队流程的才委派(带验收标准、owner 与独立复核的任务,D26/D27),其余自己直接处理并说明一句理由(issue #9 / D28)。 + +### 2. 点名指挥与另外两档 + +任何时候想精确控制,直接下指令: + +```text +创建一个叫 reviewer 的队友,让它检查 README 前三段的错别字,然后汇总它的结论。 +``` + +```text +给 reviewer 发个消息:重点看中英文标点混用。 +``` + +```text +列一下现在的成员和任务状态。 +``` + +另外两档:`always` 恢复 0.5.0 之前的主动编排(从首条消息起自主拆活、组队、分派、验收,无需逐条指挥);`off` 完全关闭智能体团队(不注入任何团队上下文、不注册团队工具)。 + +模型会把这些话术映射到对应工具(`spawn_teammate` / `send_message` / `list_agents` / `team_task_list` …),你不需要记工具名。 + +### 2.1 模型与思考强度(自动跟随 Lead,无需设置) + +**0.4.0 起,成员模型只有一条路线:自动跟随 Lead 的最新已确认模型与思考强度。** 没有单独的成员模型配置——面板没有齿轮弹窗,`spawn_teammate` 没有 `model` 参数,对话也不能「让某个成员换模型」。你只需要管好 Lead 自己用什么模型,成员每轮开始执行前会自动同步。 + +```text +创建一个叫 reviewer 的队友,检查 README 前三段的错别字。 +``` + +- **同步时机**:成员每次开始执行前(首轮、后续消息唤醒、恢复团队)都先比对 Lead 最新选择(以宿主会话中的实际选择为准,0.4.1),有变化才应用,无变化零开销;运行中的成员等本轮跑完在下一轮开始时同步(不打断已有工作)。急需切换可先中断该成员,再发消息续跑。 +- **「已确认」的含义**:以你**实际提交消息时**的模型为准(宿主在保存消息时写入快照),并用会话选模记录(`/model` 命令)与主轮实际调用记录核对——三路取最新。仅在输入框里切了下拉但还没提交,不承诺同步。 +- **失败绝不静默、重试有节制(0.4.1)**:Lead 的模型无法被成员继承时(官方 coding plan、Provider 被删除/禁用、解析不出),创建/续跑会直接报错并说明原因,不会悄悄用别的模型开跑;失败原因在成员行诊断可见,待处理消息保留不丢。同一失败不会无限重试:确定性拒绝(套餐/目录外)暂停自动重试,临时故障(超时等)按 5s/15s/30s 退避最多自动重试 3 次;Lead 换回可用模型或你再发一条新消息即自动恢复交付,恢复成功后旧错误提示自动消失。 +- **创建前校验(0.4.1)**:Lead 模型不可继承时,`spawn_teammate` 在登记成员**之前**就报错——不产生 failed 成员、不占用成员名;修正 Lead 模型后原名可直接重用。 +- **不支持继承官方 coding plan(硬性边界)**:成员是独立 CLI 进程,宿主不向它下发订阅套餐(`account:*` / `builtin:*` Provider,如智谱 GLM 官方 coding plan)的凭据,因此**不支持直接继承官方 coding plan 模型配置**。Lead 正在用套餐模型时创建/续跑成员会报错;请先在 ZCode 中把 Lead 切换到自配的第三方模型(ZCode 设置 → 模型服务,添加你自己的 Provider + API Key)。 +- **队友不可用时单 agent 兜底(0.5.1;0.5.2 补齐时序)**:Lead 的已确认模型是官方套餐时,插件会每会话一次性告知 Lead「队友无法孵化」——Lead 直接自己干全部工作,不再浪费轮次去试注定失败的建队。0.5.2 起判定优先取宿主在会话开始时上报的模型,因此**全新会话在你输入第一条消息之前就已知晓**(老宿主回落到首轮提问)。提示会自动校正:你在首条消息前或会话中途把 Lead 切到第三方模型后,下一轮提问即附带一次性「队友已可用」更新;spawn 成功也始终恢复正常用队。 + +### 3. `/team` 看状态 + +会话里随时输入 `/team`:首行输出「成员 N · 共享任务 T」,随后逐行列出成员与任务(与面板词典同源同文案),并按运行环境附上面板/命令入口。刷新语义:桌面 MCP Apps 面板自动实时(订阅推送,无需手动刷新);CLI 每次重跑 `/team` 即最新。 + +**带参数 = 用团队干活**:输入 `/team <任务描述>`(如 `/team 把这段扩写成三个角色`)时,Lead 会**真的建队执行**——先建共享任务,再按职责创建或复用成员;成员认领、执行并交付,Lead 验收后汇总。不带参数时仍严格只读。 + +### 4. `/team-coordination` 重载策略 + +策略的主通道是 hook 自动注入,通常无需手动加载。两种情况会用到这个 skill: + +- 超长会话中注入的策略可能被上下文压缩掉(D24):输入 `/team-coordination`(或让模型「重新加载团队策略 skill」)即可恢复; +- 想确认当前会话按团队纪律工作时,也可以点名加载。 + +### 一次成功的样子 + +以「创建 reviewer 检查 README 错别字」为例: + +1. 会话里出现「智能体团队」面板(`spawn_teammate` 的结果携带面板打开提示,桌面上会定向打开),成员区显示 `lead`(当前会话)与 `reviewer`; +2. `reviewer` 创建并开始工作,面板/任务板出现任务与状态变化; +3. `reviewer` 完成后向 Lead 汇报,Lead(委派出去的工作先独立复核)汇总给你; +4. `reviewer` 的会话是隐藏子会话,不会和 Lead 平级出现在左侧任务栏。 + +## 工具速查(模型可见 9 个;`interrupt:false` 时 8 个;`leadMode:off` 时 0 个) + +| 工具 | 谁用 | 作用 | +|---|---|---| +| `spawn_teammate` | Lead | 创建一个有名字的持久队友(`context: fresh\|fork`;模型自动跟随 Lead,无独立参数;目标明显值得委派时再组队) | +| `send_message` | 全体 | 给另一个成员发消息:运行中在最近回合边界送达;空闲则拉起/恢复一轮 | +| `list_agents` | 全体 | 列出 Lead 与全部队友的 target 与可用状态(`inactive` = 当前无回合,不代表任务失败) | +| `interrupt_agent` | Lead | 中断一个队友当前回合,保留其待处理收件箱(**配置关闭时此工具不注册 → 8 个**) | +| `wait_agent` | 全体 | Lead 优先收取待收消息;否则等待成员/消息/任务变化(不唤醒成员;无可推进成员时返回 noProgress,超时返回 timedOut) | +| `team_task_create` | 全体 | 在共享任务板创建一条未分配任务(可带 `blocked_by` / `write_scopes`) | +| `team_task_list` | 全体 | 列出任务:状态、owner、revision、阻塞、写作用域告警(可分页/过滤) | +| `team_task_get` | 全体 | 读取单条任务的最新完整内容(改动前必读) | +| `team_task_update` | 全体 | 用 `expected_revision` 做 CAS 的任务动作:claim / release / edit / set_dependencies / complete / reopen / reassign / delete | + +另有一个 app 专用回环工具 `team_panel_call`(面板心跳/刷新/详情(**按轮摘要**);**只读通道,零变更能力**,模型不可见);诊断探针 `team_ping` 仅在 `TEAM_DEBUG_TOOLS=1` 时暴露。 + +## 配置(userConfig) + +在 **设置 → 插件 → 智能体团队** 中修改,改完对新任务生效(进行中的会话沿用启动时配置)。 + +| 配置 | 默认 | 说明 | +|---|---|---| +| `maxMembers` | 8 | 团队内 teammate 数量上限(不含 Lead,含 failed) | +| `maxTasks` | 256 | 任务板任务数量上限 | +| `maxMessageBytes` | 65536 | 成员间单条消息的最大字节数 | +| `disposalTimeoutMs` | 5000 | 团队处置(结算与回收)的超时时间 | +| `interrupt` | true | 关闭后模型只拿到 8 个工具(`interrupt_agent` 不注册) | +| `leadMode` | auto | `auto`:按需委派(建队前=普通单 agent,建队后按委派价值判断);`always`:始终主动编排;`off`:完全关闭智能体团队(不注入、0 团队工具)。旧值 `orchestrator`/`collaborator` 按 `auto` 处理(issue #9) | + +## 网络访问、依赖与副作用 + +| 项 | 申报 | +|---|---| +| 网络访问 | **无外网请求**。daemon 经 stdio 与宿主通信;teammate 与宿主 app-server 的桥接走本机进程间通道;可选伴生页(`TEAM_COMPANION=1`)仅监听本机回环 `127.0.0.1`。模型请求由宿主按你配置的 Provider 发出,与本插件无关 | +| 模型/API 依赖 | 成员由宿主自带 `zcode` CLI 驱动,逐轮自动跟随 Lead 当前模型(见 2.1);**不支持继承官方 coding plan**(套餐凭据不下发);插件自身不需要任何 API Key | +| 文件写入 | 仅写插件数据目录 `$ZCODE_PLUGIN_DATA`(`teams/`、`logs/`、`meta/`、checkpoint)与宿主任务索引的两个白名单点(成员会话隐藏 anchor、`sidebar-audit --apply`,见 D25);宿主 `db.sqlite` 一律只读 | +| 命令执行 | hooks、daemon、`team-ctl` 全部为插件自带的 Node 脚本(`runtime/*.mjs`),由宿主 Node 运行;`teammate` 为宿主 CLI 子进程;插件不执行任意 shell 命令 | +| Hooks | SessionStart / Stop / UserPromptSubmit(`hooks/hooks.json`,随启用直接生效) | +| MCP servers | `team-daemon`(stdio) | +| 第三方组件 | 内联 MCP SDK 等第三方软件及许可证见 [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md) | + +## CLI 用法 + +```bash +# /team 命令:输出团队状态文本摘要(桌面/CLI 均可用) +/team + +# 带参数 = 用团队执行该任务(建队 + 分派 + 汇总) +/team 把这段故事扩写成三个角色 + +# 直接读盘重放(与 /team 同源) +node <插件目录>/runtime/team-ctl.mjs state # 文本摘要 +node <插件目录>/runtime/team-ctl.mjs state --json # 机器可读 +node <插件目录>/runtime/team-ctl.mjs transcript # 成员会话摘要(按轮) +node <插件目录>/runtime/team-ctl.mjs widget --standalone --out /tmp/team.html --theme dark --lang zh +node <插件目录>/runtime/team-ctl.mjs tail # 跟随事件日志 +``` + +`` = `$ZCODE_PLUGIN_DATA/teams/`(CLI 下通常是 `~/.zcode/cli/plugins/data/agent-team@/teams/…`)。 + +## Node 版本要求 + +daemon、hooks 与 `team-ctl` 都由 Node 运行,要求 **Node ≥ 22**。安装前自检: + +```bash +node -v +``` + +输出应为 `v22.x` 或更高。低于 v22 时 daemon 启动自检会给出警告,面板与工具可能不可用;插件会把实际版本写进 `$ZCODE_PLUGIN_DATA/logs/daemon-lifecycle.jsonl`(字段 `node`、`nodeWarn`)。 + +## 卸载后数据怎么处理 + +**先备份,再卸载**。默认卸载会删除团队数据且不可撤销。 + +```bash +# 1) 找到插件数据目录(安装时的 dataPath;也可从 plugins list --json 读取) +DATA="$HOME/.zcode/cli/plugins/data/agent-team@" +# 2) 备份(保留任务板、成员、消息、事件日志) +tar -czf ~/agent-team-backup-$(date +%Y%m%d).tar.gz -C "$(dirname "$DATA")" "$(basename "$DATA")" +``` + +实测行为(2026-10-24 干净环境演练): + +| 入口 | 默认卸载 | 可否保留数据 | +|---|---|---| +| CLI | `zcode plugins uninstall agent-team@` **删除整个插件数据目录**(任务板、成员、消息全部消失);当前版本缓存删除,更早版本缓存与市场注册保留 | 可:`--keep-data` 保留数据目录(事件日志哈希不变),仅移除插件代码与启用项。非交互 shell 需 `--force` | +| 桌面 | 设置 → 插件 → 更多操作 → 卸载,确认框明确提示删除缓存、数据目录与配置;实测**删除数据目录内容**(空目录保留),当前版本缓存删除 | **无** UI 等价选项 | + +注意:卸载时仍打开的相关任务窗口,后续活动会在原路径**重建一个空的数据骨架**(`events.jsonl` 为 0 字节),原团队数据不会恢复;不要因为目录又出现而误判为“数据还在”。卸载后建议关闭相关任务窗口。 + +## 故障排查 + +### 1. 先确认插件在不在、启没启 + +```bash +zcode plugins list | grep agent-team +zcode plugins list --json # 看 version / rootPath / dataPath / diagnostics +``` + +桌面:**设置 → 插件** 中确认「智能体团队」开关为启用;**设置 → 钩子** 可看到它声明的三条 hook。 + +### 2. 日志位置(都在插件数据目录下) + +| 文件 | 内容 | +|---|---| +| `logs/hooks.jsonl` | 每次 SessionStart / Stop / UserPromptSubmit 的完整 env overlay 与输入摘要——**判断 hook 有没有跑就看这里** | +| `logs/daemon-lifecycle.jsonl` | daemon 启动/回收:pid、node 版本、数据目录、`nodeWarn`、SIGINT 处置 | +| `logs/provider.jsonl` | teammate 轮次与投递细节(排障用) | +| `logs/requests.jsonl`、`logs/meta-log.jsonl` | 工具调用与面板回环记录 | +| `meta/runtime-config.json` | daemon 落盘的有效配置(hook 读取同一份) | +| `teams//events.jsonl` | 团队事件日志(append-only;`team-ctl tail` 可跟随) | +| `teams//coordinator.audit.jsonl` | 协调者锁获取/释放/接任审计 | + +### 3. hook 没生效怎么查 + +1. 确认插件已启用(禁用状态下 hook 不会运行); +2. 打开一个**新会话**,然后看 `logs/hooks.jsonl` 是否新增 `sessionstart` 记录; +3. 没有记录 → 看 **设置 → 钩子** 是否列出三条 agent-team hook(SessionStart / Stop / UserPromptSubmit),以及插件是否因版本/清单问题带 `diagnostics`; +4. 有记录但模型没按团队策略行动 → 看该条记录的 `env_overlay.ZCODE_PLUGIN_ROOT` 是否指向当前安装目录;升级后旧会话仍用旧版本,需新开会话。 + +### 4. 常见现象 + +| 现象 | 原因与处理 | +|---|---| +| 安装后 `plugins list` 出现 `Duplicate plugin hooks file ignored: hooks/hooks.json` | 已知告警:manifest 的 hooks 声明与宿主自动发现同路径文件重复,宿主显式忽略;三条 hook 仍正常执行,不影响使用。计划在后续版本清理清单 | +| 队友一直 `provisioning` / 无法创建 | 看 `logs/provider.jsonl` 与 `logs/daemon-lifecycle.jsonl`;确认 `zcode` 可执行文件可被发现(`TEAM_ZCODE_BIN` 可覆盖),以及成员名额未超 `maxMembers` | +| 创建/续跑成员时报「成员无法继承 Lead 模型」 | 预期行为(0.4.0):成员模型唯一路线 = 跟随 Lead,Lead 正在用**官方 coding plan 套餐**(`account:*`/`builtin:*`)或 Provider 已删除/禁用时直接报错,绝不静默换模型。处理:把 Lead 切到自配第三方模型(ZCode 设置 → 模型服务)后重试。0.4.1:spawn 在登记成员前即预检报错(不占成员名);续跑失败后同一失败不会无限重试(确定性拒绝暂停 / 临时故障 5s/15s/30s 退避×3),Lead 换回可用模型或发新消息即自动恢复交付,旧错误提示随之清除 | +| 桌面工具调用挂起或 `Client closed` | 已知宿主限制(D11):桌面 callTool 在 daemon 空闲回收后不重建连接。新开一个任务、立刻发起调用可命中存活 daemon;面板心跳已尽量保活 | +| 面板数字不动 | 面板靠订阅+心跳刷新;`/team` 或 `team-ctl state` 可交叉验证真实状态。桌面卡片/静态视图不探测活性,成员状态偏保守 | +| 升级后行为没变 | 宿主按会话固定插件运行时:升级后请新开任务;CLI 更新提示 “Restart zcode to apply” 同理 | +| 旧团队会话出现在左侧任务栏 | 旧数据遗留:`node runtime/team-ctl.mjs sidebar-audit --apply` 归档(默认 dry-run,可复核) | +| 团队持久记录损坏 | 报 `persisted Agent Teams … payload is invalid`。先备份 `teams//`,再用 `team-ctl state` 复核;不要手工改 `events.jsonl`(会破坏 seq 连续性) | + +### 5. 安全清理数据目录 + +确认不再需要历史团队后,可整体删除 `$ZCODE_PLUGIN_DATA`(等价于默认卸载的数据处置)。**删除前先备份**;删除后无法恢复任务板与消息。 + +## 限制与偏差(用户可读版,D1–D27) + +本插件是 ZCode 上对 DSH Agent Teams 的复刻。以下差异均为**已登记、已验收**的适配项,来自《04-能力映射与差距分析》D1–D27(编号以该台账为准)。 + +| 编号 | 你会看到什么 | +|---|---| +| D1 | 团队事件写在插件自己的数据目录(JSONL),不写进 Lead 会话日志;会话导出/回滚不包含团队事件 | +| D2 | “运行中插话”只能在下一次回合边界送达(宿主没有 steer 原语);目标运行中时消息排队,不会被丢弃或重复 | +| D3 | `context:"fork"` 在无法真正 fork 时用“fresh + Lead 已完成回合转录(截断)”实现;不是 KV 前缀共享 | +| D4 | 主 UI 是会话内 MCP Apps 面板;没有原版的头部 hover 按钮/弹层/pin;`::visualize` 快照卡片仅桌面可用 | +| D5 | 成员会话默认不进左侧任务栏;面板内提供成员会话查看视图(只读)。旧版遗留的可见行可用 `sidebar-audit` 归档 | +| D6 | Lead 仍能看见宿主内置 Task 工具(无法禁用);teammate 侧已禁用 Task,团队工具优先由策略引导 | +| D7 | 策略文本中“文件版本冲突”一句替换为 ZCode 文件工具的等价语义;其余逐字 | +| D8 | 协调者是“瞬时”的:daemon 空闲会被宿主回收,任一实例可接任;协调者交替的瞬间可能出现 `TEAM_DISPOSED` 临时错误,重试即可(真崩溃实测接任 ≤5s;〔D32〕心跳过期但进程仍存活时按 PID 存活判定宽限复核,不抢活人) | +| D9 | 没有 SessionEnd hook:处置靠 daemon 退出时尽力执行 + 下次启动对账;极短宽限下可能只留下可对账的状态 | +| D10 | 策略通过 SessionStart hook 注入到消息上下文,而非系统提示;注入文本不落 transcript;被禁用 hook 时会有 fail-loud 警告 | +| D11 | 桌面 callTool 在 daemon 被回收后可能挂起/`Client closed` 且本会话不恢复;新任务可恢复。teammate 走独立进程不受影响 | +| D13 | 工具条目不声明 `outputSchema`(宿主限制);输出契约由测试锚定 | +| D14 | 身份缺失时错误消息里用 `` 占位 | +| D15 | 参数类型错误返回 `TEAM_INVALID_ARGUMENT`,消息为 `param "" must be …`;这些是工具面消息,错误码仍属既有 27 码 | +| D16 | 同一团队由两个 daemon 服务时(代理模式):`list_agents` 的 active 成员可能保守显示 `inactive`;`wait_agent` 由协调者统一收件并判断 noProgress | +| D17 | daemon 空闲回收默认**不终止**队友轮次(keep 休眠态);如需要彻底回收可设 `TEAM_DRAIN_ON_DISPOSE=kill` | +| D18 | 给 Lead 的“已送达”以 hook 注入回执为准(宿主无直达注入原语,注入不落 transcript);对外仍是 `{sent:true}` | +| D19 | hook 读取 daemon 落盘的配置;首次 daemon 启动前 hook 使用默认值(如 `interrupt=true`) | +| D20 | 空闲 Lead 的唤醒是灰度功能:默认不拉起新回合,消息持久待命;`TEAM_WAKE_LEAD=1` 才启用 | +| D21 | 静态卡片无活性探测:成员状态按 phase 保守映射(active→inactive、lead 恒 inactive);实时面板/伴生面板才显示 running | +| D22 | 诊断工具 `team_ping` 默认不在模型工具列表(模型面 9 个,`interrupt:false` 时 8 个);`TEAM_DEBUG_TOOLS=1` 才暴露 | +| D23 | 历史事件名/旧 checkpoint 自动兼容:旧 `team/message` 归一为 `team/message/queued`,旧 delivered 结构归一为字符串数组;历史团队数据可读 | +| D24 | 策略文本在 SessionStart(startup/resume)注入;Lead 极长会话中途可能因上下文压缩丢失,可重新加载 skill 或开新任务 | +| D25 | 插件只写宿主任务索引的两个白名单点(会话隔离 anchor 墓碑、`sidebar-audit --apply`);`db.sqlite` 一律只读 | +| D26 | `always` 档(0.5.0 前的默认 `orchestrator`):主动组队/分配/独立验收,不亲自实现(除一行级修复或无人可派) | +| D27 | 任务 `complete` 是“提交”,Lead 需独立复核后才算验收完成;失败会 `reopen` 并附具体问题,通过则在任务描述里追加验收记录 | +| D28 | 0.5.0 起默认 `auto`(issue #9):建队前不注入任何模式段;首个队友创建后注入按需段(委派价值判断+正反例);`off` 完全停注入并注销团队工具;旧值 `orchestrator`/`collaborator` 统一迁移 `auto`;0.5.0 前的 runtime-config 落盘视为过期 | +| D29 | Lead 已确认模型为官方套餐时(issue #5),hook 每会话一次性注入单 agent 兜底提示(自己干全部工作、不试 spawn;非永久——后续 spawn 成功即恢复正常用队);spawn 报错同步给出该出路;检测乐观(未知/读库失败绝不触发提示) | +| D30 | 0.5.2:兜底提示优先依据宿主传给 SessionStart hook 的 `model` 载荷判定(全新会话启动即知晓;db 三源探针为回落),此后每轮提问与 db 对账——db 一旦确认非套餐模型,一次性注入撤回提示恢复正常用队 | +| D31 | 0.5.2:构建对全部 runtime 产物跑 `node --check`,失败自动整体重建 ≤3 次;发布打包对 staged 与解包树再校验一次(防外置/慢卷落盘撕裂) | + +## 文档 + +- [使用手册(截图版)](docs/使用手册.md) +- [Repo Wiki:架构、流程与源码导航(仅源码仓库,不随插件包分发)](docs/repo-wiki.md) +- 内部移交(源码仓库 `docs/`,不随包分发):`架构说明-as-built.md`、`运维手册.md`、`测试手册.md` +- [变更记录](CHANGELOG.md)、[许可证](LICENSE)、[第三方声明](THIRD-PARTY-NOTICES.md) +- 源码仓库: diff --git a/external_plugins/agent-team/THIRD-PARTY-NOTICES.md b/external_plugins/agent-team/THIRD-PARTY-NOTICES.md new file mode 100644 index 00000000..ebb84529 --- /dev/null +++ b/external_plugins/agent-team/THIRD-PARTY-NOTICES.md @@ -0,0 +1,312 @@ +# Third-Party Notices + +agent-team 的构建产物内联了下列第三方软件(esbuild bundle 进 `runtime/team-daemon.mjs`、 +`runtime/team-hooks.mjs`、`runtime/team-ctl.mjs`、`runtime/ui/team-panel.html` 与 +`runtime/ui/team-companion.html`)。各组件保留其原始许可证;本文件随发布包分发。 + +| Package | Version | License | Copyright | +|---|---|---|---| +| `@modelcontextprotocol/ext-apps` | 1.7.5 | Apache-2.0(见下,上游 package.json 标为 MIT) | MCP project contributors | +| `@modelcontextprotocol/sdk` | 1.32.1 | MIT | Copyright (c) 2024 Anthropic, PBC | +| `zod` | 3.25.76 | MIT | Copyright (c) 2025 Colin McDonnell | +| `zod-to-json-schema` | 3.25.2 | ISC | Copyright (c) 2020, Stefan Terdell | +| `ajv` | 8.20.0 | MIT | Copyright (c) 2015-2021 Evgeny Poberezkin | +| `ajv-formats` | 3.0.1 | MIT | Copyright (c) 2020 Evgeny Poberezkin | +| `fast-deep-equal` | 3.1.3 | MIT | Copyright (c) 2017 Evgeny Poberezkin | +| `json-schema-traverse` | 1.0.0 | MIT | Copyright (c) 2017 Evgeny Poberezkin | +| `fast-uri` | 3.1.8 | BSD-3-Clause | Copyright (c) 2011-2021, Gary Court; 2021-present The Fastify team | + +版本由 `package-lock.json` 锁定,构建使用 `npm ci`。 + +## MIT License + +Applies to `@modelcontextprotocol/sdk`, `zod`, `ajv`, `ajv-formats`, `fast-deep-equal`, +`json-schema-traverse` (copyright holders listed in the table above). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## ISC License — `zod-to-json-schema` + +Copyright (c) 2020, Stefan Terdell + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +## BSD-3-Clause License — `fast-uri` + +Copyright (c) 2011-2021, Gary Court until https://github.com/garycourt/uri-js/commit/a1acf730b4bba3f1097c9f52e7d9d3aba8cdcaae +Copyright (c) 2021-present The Fastify team +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +## Apache-2.0 — `@modelcontextprotocol/ext-apps` 1.7.5 + +The upstream `LICENSE` file of `@modelcontextprotocol/ext-apps@1.7.5` is reproduced +verbatim below. Its `package.json` declares `"license": "MIT"`, while the distributed +`LICENSE` is the MCP project's MIT-to-Apache-2.0 transition text followed by the +Apache License 2.0. Both are reproduced here as shipped upstream. + +``` +The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0. + +Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License. + +No rights beyond those granted by the applicable original license are conveyed for such contributions. + +--- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright + owner or by an individual or Legal Entity authorized to submit on behalf + of the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +--- + +MIT License + +Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +Creative Commons Attribution 4.0 International (CC-BY-4.0) + +Documentation in this project (excluding specifications) is licensed under +CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for +the full license text. +``` diff --git a/external_plugins/agent-team/commands/team.md b/external_plugins/agent-team/commands/team.md new file mode 100644 index 00000000..fb927fb1 --- /dev/null +++ b/external_plugins/agent-team/commands/team.md @@ -0,0 +1,95 @@ +--- +description: 智能体团队 · 状态摘要与面板入口 +allowed-tools: Bash +--- + +/team 命令(stage-5 T5.4):输出团队状态文本摘要,并按运行环境给出对应载体的入口。 +(`team_panel_call` 为 app 专用回环工具(visibility:["app"]),模型不可调。) + +**两种用法(2026-11-02 起)**: +- `/team`(无参数)= **只读**状态摘要与面板入口。 +- `/team <任务描述>`(带参数)= **直接用团队执行该任务,不输出状态摘要**(见步骤 6)。 + 用户输入 `/team` 后跟内容时,意图就是「用团队做这件事」——不要只读状态后自行代劳。 + +## 执行步骤 + +1. **读团队数据(主通道 = MCP 工具,不要猜目录)**: + 分别调用 `list_agents`(空参数)与 `team_task_list`(空参数;需全量时加 `limit: 100`)。 + 这两个工具的团队身份由宿主 `_meta.session_id` 解析,**与会话环境变量无关**,因此是唯一 + 可靠的取数通道。 + - 若任一工具返回 `TEAM_NOT_MEMBER`/报错 → 直接输出 `Team 暂不可用`(en: `Team is unavailable`), + 不要尝试用 Bash 猜目录。 + - **带参 `/team <任务>` 时**:读数据仅用于内部判断(是否需要建队、成员是否已存在), + **不输出状态摘要**(步骤 3 跳过),直接执行步骤 6。 +2. **定位 teamDir(仅用于渲染 CLI 指引,失败可省略该段)**: + 优先用当前 hook/daemon 环境里的 `TEAM_PLUGIN_DATA`(`printf '%s' "${TEAM_PLUGIN_DATA:-}"`); + 取到则 ` = /teams/`。 + **禁止**用「最近修改的 `agent-team*/teams/` 目录」当兜底——多副本并存时会跨数据根捞到 + 别的插件的团队(2026-11-02 实测事故:/team 显示了另一个会话的成员,Lead 据此空转)。 + 取不到 `TEAM_PLUGIN_DATA` → 省略「CLI 细节」段,仅输出摘要与面板入口。 +3. **输出文本摘要**(**仅无参 `/team` 时输出**;带参 `/team <任务>` 跳过此步直接执行步骤 6): + - JSON 的 `failure` 非空 → 首行 `团队持久记录无效:`(en: `Invalid persisted Team record: `),随后照常列最后有效状态; + - 正常 → 首行 `成员 N · 共享任务 T`;成员逐行 `- — `(lead/active/provisioning/failed); + 任务逐行 `- — <待处理|进行中|已完成>(Owner: )`; + 空任务板 → `暂无共享任务,可以通过对话创建`。 + - en 环境用英文词典值(Members/Shared tasks/Pending/In progress/Completed/Owner/Unowned)。 +4. **按运行环境追加载体指引**(**仅无参 `/team` 时输出**;带参 `/team <任务>` 跳过此步): + - **桌面(ZCode Desktop 会话)**:提示「打开面板:会话右侧『+』→『查看所有插件』→『个人』→『智能体团队』→『打开』;宿主『新标签页』里含『智能体团队』入口时可直接从『新标签页』打开 + (自动实时:订阅推送 ≤1s,无需刷新)」;spawn_teammate 工具已携带 `_meta.ui.surface` 定向打开提示; + - **桌面内容引用(用户要求可视化卡片时)**:用 Bash 执行 + `node widget --out <会话可视化目录>/team-widget.html --theme --lang `, + 然后在回复中单独一行输出内容引用(手动刷新 = 重跑 /team): + ::visualize{"path":"<--out 的绝对路径>","title":"智能体团队"} + - **CLI 细节指引(仅在步骤 2 拿到 `TEAM_PLUGIN_DATA` 时输出)**:headless/TUI 会话可能不暴露运行环境, + 误判会漏掉终端用户必需的入口,因此摘要后附: + `细节:node state `; + `成员会话:node transcript (按轮摘要:用户指令 + 动作组 + 每轮结论)`; + `高保真(可选):TEAM_COMPANION=1 的 daemon 在场时 node open-panel;或 + node widget --standalone --out /tmp/team-panel.html 后浏览器打开`。 + - **`` 直接执行**:`runtime/team-ctl.mjs` 自带自执行入口(`node /team-ctl.mjs …` + 可用);`scripts/team-ctl.mjs` 薄启动器等价。两者任选,不要只导出不执行。 +5. **刷新语义**(用户问「怎么刷新」时回答):MCP Apps 面板 = 自动实时(订阅推送 ≤1s); + ::visualize 卡片 = 手动(重跑 /team 重渲染);CLI 摘要 = 随轮次(每次 /team 即最新)。 + **带参 `/team <任务>` 时**:跳过步骤 3–5,直接执行步骤 6。 +6. **带参数时的团队执行(`/team <任务描述>`)**——**直接建队执行,不输出状态摘要**: + 1. 先判断该任务是否值得分工:需要多角色 / 可并行 / 写域互不相交 → 建队; + **用户已经用 `/team <任务>` 明确表达「用团队做」的意图,这就是委派信号本身**, + 不要再以「任务简单」为由自行代劳;只有确实单角色即可完成(如一句话问答)时, + 才用一行说明「这个任务不需要分工」并直接给出结果。 + **不要输出「成员 N · 共享任务 T」等状态摘要**——用户要的是团队干活,不是看状态。 + 2. 先用 `team_task_create` 为每个委派单元建共享任务,写清验收标准; + 文件改动填 `write_scopes`,先后依赖填 `blocked_by`。初始 prompt、角色说明或产出文件 + 都不能替代任务板记录。 + 3. 建队:`spawn_teammate` 创建所需成员(名字体现角色,`description` 写职责); + `prompt` 提供完整背景、任务 ID,要求先 get 最新 revision、确认 ready 再 claim, + 然后执行、自检、complete,并通过 `send_message` 向 lead 交付结果。 + 复用已有成员时发送相同的任务指引;被依赖阻塞的成员汇报阻塞后结束本轮, + 依赖完成后 Lead 再发消息唤醒(任务就绪不会自动唤醒成员)。 + 4. 用 `wait_agent` 收取成员消息,包括成员已 inactive 时的待收结果;先处理返回的 + `messages`,再通过 `list_agents` / `team_task_list` 核对状态。没有消息且无可推进的 + 成员时会立即返回 noProgress;仅在确实还需执行或补充结果时才发后续消息。 + 5. 收齐产出后由 Lead 独立核验;通过则在任务 description 记录验收结论,失败则 + reopen 并附具体问题,再通知成员返工。最后汇总答复;用消息和任务板交付纯文本结果, + 不为绕过收件箱而额外创建中转文件。 + 6. **`spawn_teammate` 失败时(套餐模型不可继承)**:不要静默改自干—— + 用一行说明「当前 Lead 模型为官方套餐,队友无法继承,本次由我直接完成」, + 然后自己完成,并提示用户可切换到自配第三方模型后再用团队。 + 7. **`spawn_teammate` 返回 `creation:"pending"` 或失败时(其他原因,如 provisioning/RPC 超时)**: + - pending = 原成员已登记、仍在 provisioning,**不是可执行成员**:用 `list_agents` / `wait_agent` + 观察同一成员;不要重复 spawn 或换名重建。若诊断显示自动确认已停止,明确告诉用户需要接管, + 且旧 turn 可能仍在执行,不要自动重复启动首轮。 + - 明确失败时用一行说明原因及接管方式,再由 Lead 决定直接完成或等待用户指示; + 不因 RPC 超时断言「宿主未创建」。 + +## 纪律 + +- **无参数时严格只读**:`/team` 不创建/修改/删除任务或成员。 +- **带参数时必须真的建队执行**(步骤 6):只输出状态、然后把活自己干,是本命令明令禁止 + 的行为(2026-11-02 用户实测体感问题:连输两次 `/team <任务>` 都没建队)。 +- 成员/任务数据**只来自 MCP 工具**(`list_agents` / `team_task_list`);Bash 侧只用于渲染 + 可选的 CLI 指引,绝不用于推断团队内容。 +- **不得跨副本猜目录**:禁止用「`agent-team*/teams/` 最近修改目录」等 glob 兜底。多副本并存 + (dev 直载 + 市场副本)时该兜底会读到别的插件的团队,导致 Lead 依据错误成员列表行动 + (2026-11-02 实测事故)。拿不到 `TEAM_PLUGIN_DATA` 就省略 CLI 段。 +- `` 不存在 = 尚无团队事件(隐式 Lead),按空团队摘要输出,不报错。 +- 路径定位失败 → 省略 CLI 细节段,仅输出摘要与面板入口(不阻塞、不猜测路径)。 diff --git a/external_plugins/agent-team/docs/assets/manual/card-dark.png b/external_plugins/agent-team/docs/assets/manual/card-dark.png new file mode 100644 index 00000000..e9337edd Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/card-dark.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/card-light.png b/external_plugins/agent-team/docs/assets/manual/card-light.png new file mode 100644 index 00000000..ce0b3df9 Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/card-light.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/cli-text-summary.png b/external_plugins/agent-team/docs/assets/manual/cli-text-summary.png new file mode 100644 index 00000000..f0c3d7d8 Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/cli-text-summary.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/cli-version.png b/external_plugins/agent-team/docs/assets/manual/cli-version.png new file mode 100644 index 00000000..8e36210b Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/cli-version.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/market-personal.png b/external_plugins/agent-team/docs/assets/manual/market-personal.png new file mode 100644 index 00000000..dfac67d0 Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/market-personal.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/market-sources.png b/external_plugins/agent-team/docs/assets/manual/market-sources.png new file mode 100644 index 00000000..fca861d7 Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/market-sources.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/panel-final.png b/external_plugins/agent-team/docs/assets/manual/panel-final.png new file mode 100644 index 00000000..1e046bce Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/panel-final.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/panel-running.png b/external_plugins/agent-team/docs/assets/manual/panel-running.png new file mode 100644 index 00000000..eca84b26 Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/panel-running.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/settings-enabled.png b/external_plugins/agent-team/docs/assets/manual/settings-enabled.png new file mode 100644 index 00000000..dc6241cd Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/settings-enabled.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/tool-permission.png b/external_plugins/agent-team/docs/assets/manual/tool-permission.png new file mode 100644 index 00000000..0b3203b7 Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/tool-permission.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/uninstall-confirm.png b/external_plugins/agent-team/docs/assets/manual/uninstall-confirm.png new file mode 100644 index 00000000..581a9eff Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/uninstall-confirm.png differ diff --git a/external_plugins/agent-team/docs/assets/manual/update-available.png b/external_plugins/agent-team/docs/assets/manual/update-available.png new file mode 100644 index 00000000..3ebe2adf Binary files /dev/null and b/external_plugins/agent-team/docs/assets/manual/update-available.png differ diff --git "a/external_plugins/agent-team/docs/\344\275\277\347\224\250\346\211\213\345\206\214.md" "b/external_plugins/agent-team/docs/\344\275\277\347\224\250\346\211\213\345\206\214.md" new file mode 100644 index 00000000..11926eb0 --- /dev/null +++ "b/external_plugins/agent-team/docs/\344\275\277\347\224\250\346\211\213\345\206\214.md" @@ -0,0 +1,166 @@ +# 使用手册(Agent Teams) + +本手册配截图说明安装、启用、面板、`/team` 与卡片两种 CLI 形态、升级与卸载。命令与配置的完整说明见 [README](../README.md)。 + +- 宿主基线:ZCode Desktop 3.16.2 / CLI 0.17.0(终验实测);发布演练在 Desktop 3.16.3 / CLI 0.17.0 复测。 +- 截图版本:cli-* 与 card-* 采集于 **0.1.2** 安装实例;panel-*、settings-*、market-*、update-*、uninstall-* 采集于发布演练实例(0.1.0/0.1.1)。 + **0.1.2 为文档变更版**:`dist/` 与 0.1.1 逐字节相同(`team-panel.html` sha256 `6c7a14a0…`),因此上列桌面截图与 0.1.2 的实际 UI 完全一致。详见文末「截图与版本」。 + +## 1. 安装与启用 + +### 1.1 添加本地/团队市场并安装 + +1. 打开 **插件市场** → **添加** → **添加插件市场**。 +2. 粘贴市场根目录(**含 `marketplace.json` 的那层**,不是插件子目录),点 **添加插件市场**。 +3. 切到 **个人**,找到「智能体团队」,点 **安装**。 + +![市场个人页:智能体团队](assets/manual/market-personal.png) + +### 1.2 在设置中确认启用 + +**设置 → 插件** 的已安装列表中出现「智能体团队」,右侧开关为启用状态。hooks(SessionStart / Stop / UserPromptSubmit)随启用自动生效,无需额外开关或信任授予;可在 **设置 → 钩子** 查看这三条声明。 + +![设置 → 插件:已启用](assets/manual/settings-enabled.png) + +### 1.3 CLI 安装(可选) + +```bash +zcode plugins marketplace add /path/to/market-root +zcode plugins install agent-team@ +zcode plugins enable agent-team@ +zcode plugins list | grep -A2 agent-team # 确认版本与缓存路径 +``` + +![CLI:确认安装版本 0.1.2](assets/manual/cli-version.png) + +## 2. 快速上手 + +新建任务(旧任务不会刷新插件能力),发送: + +```text +创建一个叫 reviewer 的队友,让它检查 README 前三段的错别字,然后汇总它的结论。 +``` + +Lead 会创建 `reviewer`、分配任务,并在会话内渲染「智能体团队」面板;`reviewer` 完成后把结论发回,Lead 汇总给你。下图为首次运行时面板与 Lead 的进度: + +![会话内面板:成员 2(lead / reviewer)运行中](assets/manual/panel-running.png) + +桌面默认权限模式下,首次调用团队工具会弹出权限确认;选择「允许(仅本次)」或「始终允许本项目」即可。这是宿主的工具授权,与 hook 无关。 + +![工具权限确认](assets/manual/tool-permission.png) + +任务完成时,Lead 的最终答复与面板同屏可见: + +![任务完成:Lead 汇总与面板](assets/manual/panel-final.png) + +### 2.1 模型与思考强度(自动跟随 Lead,无需设置) + +**0.4.0 起,成员模型只有一条路线:自动跟随 Lead 的最新已确认模型与思考强度。** 没有单独的成员模型配置:面板没有齿轮弹窗,`spawn_teammate` 没有 `model` 参数,也不能在对话里「让某个成员换模型」。你只需要管好 Lead 的模型,成员每次开始执行前自动同步(运行中的成员等本轮跑完在下一轮开始时同步,不会被打断;急需切换可先中断该成员再发消息)。 + +> **硬性边界:不支持继承官方 coding plan 模型配置。** 成员是独立 CLI 进程,宿主不向它下发订阅套餐(`account:*` / `builtin:*` Provider,如智谱 GLM 官方 coding plan)的凭据。Lead 正在用套餐模型时创建/续跑成员会**直接报错并说明原因**(绝不悄悄换模型开跑);请先在 ZCode 设置 → 模型服务中把 Lead 切换到自配的第三方模型。 + +> 「已确认」= 三路取最新:你提交消息时宿主写入的模型快照、会话选模记录(`/model` 命令更新)、主轮实际调用记录。仅在输入框里切了下拉但还没提交消息,不承诺同步。 + +**0.4.1 修复轮补充**(跟随机制的可靠性,无新配置项): + +- 一致性判断以**宿主会话中的实际选择**为准(`origin` 记录只是辅助):崩溃恢复后不会凭旧记录误判「已一致」;仅思考强度变化同样会同步;首轮已定模的不重复应用。 +- 同步失败**可见且有节制**:失败原因在成员行诊断与 `model-failed.json` 可见,待处理消息保留不丢。确定性拒绝(套餐/目录外/宿主明确不支持)暂停相同选择的自动重试;临时故障(超时/进程异常)按 5s/15s/30s 退避、最多自动重试 3 次;**Lead 换回可用模型或你再发一条新消息即解锁**,恢复成功后旧错误提示自动消失。 +- **创建前校验**:Lead 模型不可继承时 `spawn_teammate` 在登记成员之前就报错——不产生 failed 成员、不占用成员名,修正 Lead 模型后原名可直接重用。 + +## 3. 面板说明 + +「智能体团队」面板是插件的主 UI(MCP Apps surface `agent-team-panel`),由宿主在会话内渲染,数据通过 `resources/subscribe` 实时推送。 + +| 区域 | 内容 | +|---|---| +| 成员 | Lead 与全部 teammate;名字、角色、状态点(运行中 / 未运行 / 创建中 / 失败)。Lead 行标「当前会话」;成员行显示实际生效模型(跟随 Lead),继承失败时显示一行诊断 | +| 共享任务 | 任务标题、状态(待处理 / 进行中 / 已完成)、Owner、展开查看描述与验收记录 | +| 通知条 | 新消息、任务变化等提示(有变化时出现) | +| 刷新 | 订阅推送 ≤1s 自动刷新;面板心跳每 25s 一次,兼作 Lead 侧连接保活 | + +成员卡片可打开成员会话查看视图(只读:按页载入成员转录,带 events/delivered 徽标)。视图按轮显示用户指令、动作组(可点开逐条工具)与每轮结论;不展示全量转录(需要原始记录时用 `team-ctl`/事件日志)。静态卡片按保守口径映射活性(active→未运行),实时面板才显示运行中。 + +> 面板是**只读通道**(0.4.0 起恢复零变更能力口径):不提供任何模型/配置修改入口;所有变更都通过对话由 Lead 执行。 + +## 4. CLI:文本摘要(形态一) + +CLI 会话没有图形面板,`/team` 命令输出文本摘要;其数据面与 `team-ctl state` 同源: + +```bash +/team +# 或直接读盘重放 +node <插件目录>/runtime/team-ctl.mjs state +``` + +输出包含团队/会话、成员表、任务表、消息投递统计: + +![CLI 文本摘要(team-ctl state;/team 同源)](assets/manual/cli-text-summary.png) + +常用子命令: + +```bash +node <插件目录>/runtime/team-ctl.mjs state --json # 机器可读 +node <插件目录>/runtime/team-ctl.mjs transcript # 成员会话摘要(按轮) +node <插件目录>/runtime/team-ctl.mjs tail # 跟随事件日志 +``` + +## 5. CLI:卡片(形态二) + +`team-ctl widget` 生成与面板同源的静态卡片,可作为独立 HTML 打开或嵌入内容引用: + +```bash +node <插件目录>/runtime/team-ctl.mjs widget --standalone \ + --theme dark --lang zh --out /tmp/team-card.html +open /tmp/team-card.html +``` + +深色: + +![静态卡片(dark / zh)](assets/manual/card-dark.png) + +浅色: + +![静态卡片(light / zh)](assets/manual/card-light.png) + +> 卡片为静态快照,不探测活性:成员状态显示为「未运行」属预期(限制 D21)。桌面里也可以让 Lead 生成 `::visualize` 内容引用卡片。 + +## 6. 升级 + +源码或市场目录更新后,**改源码不会热更新**,按以下步骤升级: + +1. 插件市场 → 右上 **市场源** → 找到你的市场 → **刷新该市场**; +2. 回到 **个人**,插件卡片出现「可更新」→ 点 **更新**; +3. 升级后**新开任务**才使用新版本(宿主按会话固定插件运行时)。 + +![市场源:刷新市场](assets/manual/market-sources.png) + +![个人页:可更新](assets/manual/update-available.png) + +## 7. 卸载与数据 + +卸载前先备份插件数据目录(默认卸载会删除团队数据): + +```bash +DATA="$HOME/.zcode/cli/plugins/data/agent-team@" +tar -czf ~/agent-team-backup-$(date +%Y%m%d).tar.gz -C "$(dirname "$DATA")" "$(basename "$DATA")" +``` + +桌面:**设置 → 插件 → 智能体团队 → 更多操作 → 卸载**。确认框会提示删除缓存、数据目录与配置: + +![卸载确认框](assets/manual/uninstall-confirm.png) + +- CLI 默认卸载删除整个数据目录;需要保留数据用 `--keep-data`(非交互 shell 加 `--force`)。 +- 桌面无「保留数据」选项;卸载后请关闭仍打开的相关任务窗口,否则旧会话可能重建一个**空**数据骨架(`events.jsonl` 0 字节,原数据不恢复)。 +- 完整结论与备份指引见 [README「卸载后数据怎么处理」](../README.md#卸载后数据怎么处理)。 + +## 8. 截图与版本 + +| 截图 | 采集对象 | 采集时间 | 说明 | +|---|---|---|---| +| `cli-version.png`、`cli-text-summary.png`、`card-dark.png`、`card-light.png` | 0.1.2 安装实例(隔离 HOME) | 2026-10-24 | CLI 文本摘要与卡片由 0.1.2 的 `team-ctl` 实际生成;卡片用 Chromium 打开真实 standalone HTML 截图 | +| `panel-running.png`、`panel-final.png`、`tool-permission.png` | 发布演练实例(0.1.0 运行时) | 2026-10-24 | 面板/权限 UI | +| `settings-enabled.png`、`market-personal.png`、`market-sources.png`、`update-available.png`、`uninstall-confirm.png` | 发布演练实例(0.1.0→0.1.1) | 2026-10-24 | 市场与设置 UI | + +版本一致性依据:0.1.2 与 0.1.1 的 `dist/` 逐字节相同(含 `dist/ui/team-panel.html`,sha256 `6c7a14a0e71dbea5cfb0014fa0e37ef0f794f047233d417f9df9d5fa4a743ad2`),0.1.2 仅改文档、清单版本与包内文档资源;上述 UI 截图中的布局与文案与当前版本一致,且截图中不显示会随版本变化的版本号字段。 + +> 采集限制:采集桌面截图时,演示机屏幕随后被锁定,无法再驱动桌面 UI 重拍;因此桌面截图为同一次发布演练的原始实拍(运行时 0.1.0/0.1.1),并以 `dist` 逐字节相同证明与 0.1.2 UI 一致。此事实同时登记在《最终验收汇总》V02 证据说明与 stage-7 勘误中。 diff --git a/external_plugins/agent-team/hooks/hooks.json b/external_plugins/agent-team/hooks/hooks.json new file mode 100644 index 00000000..b8adaa92 --- /dev/null +++ b/external_plugins/agent-team/hooks/hooks.json @@ -0,0 +1,41 @@ +{ + "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume", + "hooks": [ + { + "type": "command", + "command": "node \"${ZCODE_PLUGIN_ROOT}/runtime/team-hooks.mjs\"", + "timeout": 15, + "statusMessage": "agent-team SessionStart(策略/收件箱注入)" + } + ] + } + ], + "Stop": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${ZCODE_PLUGIN_ROOT}/runtime/team-hooks.mjs\"", + "timeout": 15, + "statusMessage": "agent-team Stop(回合边界交付)" + } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${ZCODE_PLUGIN_ROOT}/runtime/team-hooks.mjs\"", + "timeout": 15, + "statusMessage": "agent-team UserPromptSubmit(收件箱兜底注入)" + } + ] + } + ] + } +} diff --git a/external_plugins/agent-team/runtime/app-server-bridge.mjs b/external_plugins/agent-team/runtime/app-server-bridge.mjs new file mode 100644 index 00000000..06f7f0d6 --- /dev/null +++ b/external_plugins/agent-team/runtime/app-server-bridge.mjs @@ -0,0 +1,76 @@ +// app-server 桥接器(stage-6 会话隔离生产资产;纯 Node 脚本,无 TS/无依赖)。 +// 用途:让 TS 侧以「常量可执行文件 + 参数数组」的合规形态孵化 `zcode app-server`, +// 并把父进程的 stdin/stdout/stderr 直接接到 app-server(NDJSON 双向流)。 +// 契约:argv[2] = spec 文件路径(JSON):{ executable, argv, cwd }(env 经 bridge 进程环境传递, +// 不落盘;旧 spec 仍可带 env) +// executable 必须为绝对路径(TS 侧已校验;此处复核)。 +// 行为:spawn(stdio: inherit) → 转发 SIGTERM/SIGINT/SIGHUP → 以子进程退出码退出; +// spawn 失败 → 写单行可读错误到 stderr → exit 127(不静默)。 +import fs from "node:fs"; +import path from "node:path"; +import { spawn } from "node:child_process"; + +const specPath = process.argv[2]; +if (typeof specPath !== "string" || specPath.length === 0) { + process.stderr.write("app-server-bridge: spec path required\n"); + process.exit(2); +} + +let spec; +try { + spec = JSON.parse(fs.readFileSync(specPath, "utf8")); +} catch (err) { + process.stderr.write(`app-server-bridge: unreadable spec (${err instanceof Error ? err.message : String(err)})\n`); + process.exit(2); +} +// spec 仍可能含 env(旧格式):读入内存后立即删除,缩短明文落盘窗口。 +try { + fs.unlinkSync(specPath); +} catch { + /* best-effort */ +} + +if (typeof spec.executable !== "string" || !path.isAbsolute(spec.executable)) { + process.stderr.write("app-server-bridge: executable must be an absolute path\n"); + process.exit(2); +} +if (!Array.isArray(spec.argv) || spec.argv.some((a) => typeof a !== "string")) { + process.stderr.write("app-server-bridge: argv must be a string array\n"); + process.exit(2); +} + +let child; +try { + child = spawn(spec.executable, spec.argv, { + cwd: spec.cwd, + env: spec.env ?? process.env, + stdio: "inherit", + }); +} catch (err) { + process.stderr.write(`app-server-bridge: spawn failed (${err instanceof Error ? err.message : String(err)})\n`); + process.exit(127); +} + +const forward = (sig) => { + try { + child.kill(sig); + } catch { + /* 子进程已退出 */ + } +}; +process.on("SIGTERM", () => forward("SIGTERM")); +process.on("SIGINT", () => forward("SIGINT")); +process.on("SIGHUP", () => forward("SIGHUP")); +process.on("exit", () => forward("SIGKILL")); + +child.on("error", (err) => { + process.stderr.write(`app-server-bridge: child error (${err.message})\n`); + process.exit(127); +}); +child.on("exit", (code, signal) => { + if (signal !== null) { + process.kill(process.pid, signal); + return; + } + process.exit(code ?? 0); +}); diff --git a/external_plugins/agent-team/runtime/detach-helper.mjs b/external_plugins/agent-team/runtime/detach-helper.mjs new file mode 100644 index 00000000..b8d445da --- /dev/null +++ b/external_plugins/agent-team/runtime/detach-helper.mjs @@ -0,0 +1,61 @@ +// 轮次进程脱离孵化器(stage-4 生产资产;纯 Node 脚本,无 TS/无依赖)。 +// 用途:以「独立进程组 + stdout 落文件」孵化 teammate 轮次进程——孵化器自身立即退出, +// daemon 不持有轮次进程任何管道(daemon 被宿主回收不连带杀轮次、无 EPIPE 面)。 +// 契约:argv[2] = spec 文件路径(JSON): +// { command, argv, cwd, stdoutFile, resultFile }(env 默认经本 helper 的进程环境传递, +// 不落盘;persistEnv=true 的旧 spec 仍可带 env) +// 行为:spawn(detached) → unref → 把 { pid } 原子写入 resultFile → exit 0; +// spawn 抛错 → 写 { error } → exit 0(错误经 resultFile 显式上抛,不静默)。 +import fs from "node:fs"; +import path from "node:path"; +import { spawn } from "node:child_process"; + +const specPath = process.argv[2]; +if (typeof specPath !== "string" || specPath.length === 0) { + process.stderr.write("detach-helper: spec path required\n"); + process.exit(2); +} +const spec = JSON.parse(fs.readFileSync(specPath, "utf8")); +// spec 仍可能含 env(persistEnv 旧格式):读入内存后立即删除,缩短明文落盘窗口。 +try { + fs.unlinkSync(specPath); +} catch { + /* best-effort */ +} +// 默认使用 helper 自身的进程环境(由 spawnDetached 以 execFile env 注入,不落盘)。 +const childEnv = spec.env ?? process.env; + +let result; +try { + fs.mkdirSync(path.dirname(spec.stdoutFile), { recursive: true, mode: 0o700 }); + const fd = fs.openSync(spec.stdoutFile, "w", 0o600); + try { + const child = spawn(spec.command, spec.argv, { + detached: true, + stdio: ["ignore", fd, fd], + env: childEnv, + cwd: spec.cwd, + }); + child.unref(); + // spawn 失败(ENOENT 等)经 'error' 事件异步上报;成功经 'spawn' 确认——二者先到者定案 + result = await new Promise((resolve) => { + const timer = setTimeout(() => resolve({ error: "spawn confirmation timeout" }), 2_000); + child.once("error", (err) => { + clearTimeout(timer); + resolve({ error: err instanceof Error ? `${err.name}: ${err.message}` : String(err) }); + }); + child.once("spawn", () => { + clearTimeout(timer); + resolve({ pid: child.pid }); + }); + }); + } finally { + fs.closeSync(fd); + } +} catch (err) { + result = { error: err instanceof Error ? `${err.name}: ${err.message}` : String(err) }; +} +const tmp = `${spec.resultFile}.tmp-${process.pid}`; +fs.writeFileSync(tmp, JSON.stringify(result), { mode: 0o600 }); +fs.renameSync(tmp, spec.resultFile); +process.exit(0); diff --git a/external_plugins/agent-team/runtime/team-ctl.mjs b/external_plugins/agent-team/runtime/team-ctl.mjs new file mode 100644 index 00000000..88fec359 --- /dev/null +++ b/external_plugins/agent-team/runtime/team-ctl.mjs @@ -0,0 +1,7093 @@ +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// src/cli/main.ts +import fs13 from "node:fs"; +import path14 from "node:path"; +import { pathToFileURL } from "node:url"; + +// src/coord/replay.ts +import fs from "node:fs"; +import path from "node:path"; + +// node_modules/zod/v3/external.js +var external_exports = {}; +__export(external_exports, { + BRAND: () => BRAND, + DIRTY: () => DIRTY, + EMPTY_PATH: () => EMPTY_PATH, + INVALID: () => INVALID, + NEVER: () => NEVER, + OK: () => OK, + ParseStatus: () => ParseStatus, + Schema: () => ZodType, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBigInt: () => ZodBigInt, + ZodBoolean: () => ZodBoolean, + ZodBranded: () => ZodBranded, + ZodCatch: () => ZodCatch, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodEffects: () => ZodEffects, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNativeEnum: () => ZodNativeEnum, + ZodNever: () => ZodNever, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodParsedType: () => ZodParsedType, + ZodPipeline: () => ZodPipeline, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSchema: () => ZodType, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodSymbol: () => ZodSymbol, + ZodTransformer: () => ZodEffects, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + addIssueToContext: () => addIssueToContext, + any: () => anyType, + array: () => arrayType, + bigint: () => bigIntType, + boolean: () => booleanType, + coerce: () => coerce, + custom: () => custom, + date: () => dateType, + datetimeRegex: () => datetimeRegex, + defaultErrorMap: () => en_default, + discriminatedUnion: () => discriminatedUnionType, + effect: () => effectsType, + enum: () => enumType, + function: () => functionType, + getErrorMap: () => getErrorMap, + getParsedType: () => getParsedType, + instanceof: () => instanceOfType, + intersection: () => intersectionType, + isAborted: () => isAborted, + isAsync: () => isAsync, + isDirty: () => isDirty, + isValid: () => isValid, + late: () => late, + lazy: () => lazyType, + literal: () => literalType, + makeIssue: () => makeIssue, + map: () => mapType, + nan: () => nanType, + nativeEnum: () => nativeEnumType, + never: () => neverType, + null: () => nullType, + nullable: () => nullableType, + number: () => numberType, + object: () => objectType, + objectUtil: () => objectUtil, + oboolean: () => oboolean, + onumber: () => onumber, + optional: () => optionalType, + ostring: () => ostring, + pipeline: () => pipelineType, + preprocess: () => preprocessType, + promise: () => promiseType, + quotelessJson: () => quotelessJson, + record: () => recordType, + set: () => setType, + setErrorMap: () => setErrorMap, + strictObject: () => strictObjectType, + string: () => stringType, + symbol: () => symbolType, + transformer: () => effectsType, + tuple: () => tupleType, + undefined: () => undefinedType, + union: () => unionType, + unknown: () => unknownType, + util: () => util, + void: () => voidType +}); + +// node_modules/zod/v3/helpers/util.js +var util; +(function(util2) { + util2.assertEqual = (_) => { + }; + function assertIs(_arg) { + } + util2.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util2.assertNever = assertNever; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util2.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType = (data) => { + const t2 = typeof data; + switch (t2) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; + +// node_modules/zod/v3/ZodError.js +var ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +var ZodError = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; + +// node_modules/zod/v3/locales/en.js +var errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "bigint") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; +var en_default = errorMap; + +// node_modules/zod/v3/errors.js +var overrideErrorMap = en_default; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} + +// node_modules/zod/v3/helpers/parseUtil.js +var makeIssue = (params) => { + const { data, path: path15, errorMaps, issueData } = params; + const fullPath = [...path15, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage + }; +}; +var EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_default ? void 0 : en_default + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue); +} +var ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +}; +var INVALID = Object.freeze({ + status: "aborted" +}); +var DIRTY = (value) => ({ status: "dirty", value }); +var OK = (value) => ({ status: "valid", value }); +var isAborted = (x) => x.status === "aborted"; +var isDirty = (x) => x.status === "dirty"; +var isValid = (x) => x.status === "valid"; +var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + +// node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); + +// node_modules/zod/v3/types.js +var ParseInputLazyPath = class { + constructor(parent, value, path15, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path15; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +}; +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +var ZodType = class { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}; +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[0-9a-z]+$/; +var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var nanoidRegex = /^[a-z0-9_-]{21}$/i; +var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var emojiRegex; +var ipv4Regex = /^(?:(?: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])$/; +var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; +var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +var dateRegexSource = `((\\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])))`; +var dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } +} +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +var ZodString = class _ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input.data = input.data.trim(); + } else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +var ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodDate = class _ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +}; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); +}; +var ZodSymbol = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); +}; +var ZodUndefined = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); +}; +var ZodNull = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); +}; +var ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); +}; +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); +}; +var ZodNever = class extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; + } +}; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); +}; +var ZodVoid = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); +}; +var ZodArray = class _ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; + } +} +var ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new _ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +}; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +var ZodUnion = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [void 0]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [void 0, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}; +var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} +var ZodIntersection = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } +}; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); +}; +var ZodTuple = class _ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}; +var ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); +}; +var ZodSet = class _ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); +}; +var ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}; +var ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); +}; +var ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class _ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return _ZodEnum.create(values, { + ...this._def, + ...newDef + }); + } + exclude(values, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); + } +}; +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); +}; +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } +}; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); +}; +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util.assertNever(effect); + } +}; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); +}; +var ZodOptional = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); +}; +var ZodNullable = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); +}; +var ZodDefault = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); +}; +var ZodCatch = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); +}; +var ZodNaN = class extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +}; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); +}; +var BRAND = Symbol("zod_brand"); +var ZodBranded = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } +}; +var ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a, b) { + return new _ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}; +var ZodReadonly = class extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +}; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); +}; +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom(check, _params = {}, fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r2) => { + if (!r2) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +var late = { + object: ZodObject.lazycreate +}; +var ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data) => data instanceof cls, params); +var stringType = ZodString.create; +var numberType = ZodNumber.create; +var nanType = ZodNaN.create; +var bigIntType = ZodBigInt.create; +var booleanType = ZodBoolean.create; +var dateType = ZodDate.create; +var symbolType = ZodSymbol.create; +var undefinedType = ZodUndefined.create; +var nullType = ZodNull.create; +var anyType = ZodAny.create; +var unknownType = ZodUnknown.create; +var neverType = ZodNever.create; +var voidType = ZodVoid.create; +var arrayType = ZodArray.create; +var objectType = ZodObject.create; +var strictObjectType = ZodObject.strictCreate; +var unionType = ZodUnion.create; +var discriminatedUnionType = ZodDiscriminatedUnion.create; +var intersectionType = ZodIntersection.create; +var tupleType = ZodTuple.create; +var recordType = ZodRecord.create; +var mapType = ZodMap.create; +var setType = ZodSet.create; +var functionType = ZodFunction.create; +var lazyType = ZodLazy.create; +var literalType = ZodLiteral.create; +var enumType = ZodEnum.create; +var nativeEnumType = ZodNativeEnum.create; +var promiseType = ZodPromise.create; +var effectsType = ZodEffects.create; +var optionalType = ZodOptional.create; +var nullableType = ZodNullable.create; +var preprocessType = ZodEffects.createWithPreprocess; +var pipelineType = ZodPipeline.create; +var ostring = () => stringType().optional(); +var onumber = () => numberType().optional(); +var oboolean = () => booleanType().optional(); +var coerce = { + string: (arg) => ZodString.create({ ...arg, coerce: true }), + number: (arg) => ZodNumber.create({ ...arg, coerce: true }), + boolean: (arg) => ZodBoolean.create({ + ...arg, + coerce: true + }), + bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), + date: (arg) => ZodDate.create({ ...arg, coerce: true }) +}; +var NEVER = INVALID; + +// src/domain/errors.ts +var TeamError = class extends Error { + code; + constructor(code, message, options) { + super(message, options); + this.name = "TeamError"; + this.code = code; + } + toJSON() { + return serializeTeamError(this); + } +}; +function serializeTeamError(err) { + const out = { name: "TeamError", code: err.code, message: err.message }; + const seen = new WeakSet([err]); + const cause = err.cause; + if (cause !== void 0 && cause !== null) out.cause = serializeCause(cause, seen); + return out; +} +function serializeCause(cause, seen) { + if (!(cause instanceof Error)) return { message: String(cause) }; + if (seen.has(cause)) return { name: cause.name, message: "[circular cause]" }; + seen.add(cause); + if (cause instanceof TeamError) { + const serialized = { + name: "TeamError", + code: cause.code, + message: cause.message + }; + const inner2 = cause.cause; + if (inner2 !== void 0 && inner2 !== null) serialized.cause = serializeCause(inner2, seen); + return serialized; + } + const plain = { name: cause.name, message: cause.message }; + const inner = cause.cause; + if (inner !== void 0 && inner !== null) plain.cause = serializeCause(inner, seen); + return plain; +} + +// src/domain/events.ts +var IMAGE_MEDIA_TYPES = ["png", "jpeg", "webp", "gif"]; +function validateContentBlock(block) { + if (typeof block !== "object" || block === null || Array.isArray(block)) { + throw new Error("content block must be a JSON object"); + } + const b = block; + switch (b.type) { + case "text": + case "reasoning": + if (typeof b.text !== "string") throw new Error(`${String(b.type)} block requires string text`); + return block; + case "image": { + const a = b.attachment; + if (typeof a !== "object" || a === null || Array.isArray(a)) { + throw new Error("image block requires object attachment"); + } + const att = a; + if (typeof att.attachmentId !== "string") throw new Error("image attachment requires string attachmentId"); + if (typeof att.mediaType !== "string" || !IMAGE_MEDIA_TYPES.includes(att.mediaType)) { + throw new Error(`image attachment mediaType must be one of ${IMAGE_MEDIA_TYPES.join("/")}`); + } + if (typeof att.bytes !== "number") throw new Error("image attachment requires number bytes"); + if (typeof att.width !== "number") throw new Error("image attachment requires number width"); + if (typeof att.height !== "number") throw new Error("image attachment requires number height"); + if (att.name !== void 0 && typeof att.name !== "string") { + throw new Error("image attachment name must be a string when present"); + } + return block; + } + case "tool-call": { + if (typeof b.id !== "string") throw new Error("tool-call block requires string id"); + if (typeof b.name !== "string") throw new Error("tool-call block requires string name"); + if (!("arguments" in b)) throw new Error("tool-call block requires arguments"); + return block; + } + case "tool-result": + throw new Error("retired tool-result wrapper is not accepted as Team message content"); + default: + return block; + } +} +var contentBlocksSchema = external_exports.array(external_exports.unknown()).superRefine((blocks, ctx) => { + for (let i = 0; i < blocks.length; i++) { + try { + validateContentBlock(blocks[i]); + } catch (err) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: [i], + message: err instanceof Error ? err.message : String(err) + }); + } + } +}); +var TASK_ID_PATTERN = /^task-(\d+)$/; +function isLooseIdValid(id) { + if (id.length === 0) return false; + const m = id.match(TASK_ID_PATTERN); + if (m && !Number.isSafeInteger(Number(m[1]))) return false; + return true; +} +function taskNumberFromId(id) { + const m = id.match(TASK_ID_PATTERN); + return m ? Number(m[1]) : void 0; +} +var looseIdSchema = external_exports.string().refine(isLooseIdValid, { message: "invalid loose id" }); +var memberSnapshotSchema = external_exports.strictObject({ + id: external_exports.string(), + name: external_exports.string(), + description: external_exports.string(), + provider: external_exports.string(), + context: external_exports.enum(["fresh", "fork"]), + phase: external_exports.enum(["provisioning", "active", "failed"]), + error: external_exports.string().optional() +}); +var taskSnapshotSchema = external_exports.strictObject({ + id: looseIdSchema, + revision: external_exports.number().refine((n) => Number.isSafeInteger(n) && n >= 1, { + message: "revision must be a positive safe integer" + }), + subject: external_exports.string(), + description: external_exports.string(), + status: external_exports.enum(["pending", "in_progress", "completed", "deleted"]), + ownerId: external_exports.string().optional(), + blockedBy: external_exports.array(external_exports.string()), + writeScopes: external_exports.array(external_exports.string()) +}); +var messageSnapshotSchema = external_exports.strictObject({ + id: looseIdSchema, + senderId: external_exports.string(), + senderName: external_exports.string(), + targetId: external_exports.string(), + content: contentBlocksSchema +}); +var TEAM_EVENT_VERSION = 2; +var TEAM_EVENT_TYPES = [ + "team/member", + "team/task", + "team/message/queued", + "team/message/delivered" +]; +var memberEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/member"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + member: memberSnapshotSchema +}); +var taskEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/task"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + task: taskSnapshotSchema +}); +var messageQueuedEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/message/queued"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + message: messageSnapshotSchema +}); +var messageDeliveredEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/message/delivered"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + messageId: external_exports.string(), + targetId: external_exports.string() +}); +var TEAM_EVENT_SCHEMAS = { + "team/member": memberEventSchema, + "team/task": taskEventSchema, + "team/message/queued": messageQueuedEventSchema, + "team/message/delivered": messageDeliveredEventSchema +}; +var LEGACY_EVENT_TYPE_ALIASES = { + "team/message": "team/message/queued" +}; +function selectTeamEvent(raw, teamId) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { kind: "ignored" }; + const candidate = raw; + const rawType = candidate.type; + if (typeof rawType !== "string") return { kind: "ignored" }; + const eventType = TEAM_EVENT_TYPES.includes(rawType) ? rawType : LEGACY_EVENT_TYPE_ALIASES[rawType]; + if (eventType === void 0) return { kind: "ignored" }; + if (typeof candidate.teamId !== "string" || candidate.teamId !== teamId) { + return { kind: "ignored" }; + } + if (candidate.version !== TEAM_EVENT_VERSION) { + return { kind: "unsupported-version", version: candidate.version }; + } + const normalized = rawType === eventType ? raw : { ...candidate, type: eventType }; + const parsed = TEAM_EVENT_SCHEMAS[eventType].safeParse(normalized); + if (!parsed.success) return { kind: "invalid-payload", type: eventType }; + return { kind: "event", event: parsed.data }; +} +var deliveredIdsSchema = external_exports.preprocess((value) => { + if (!Array.isArray(value)) return value; + return value.map((item) => { + if (typeof item === "string") return item; + if (typeof item === "object" && item !== null && typeof item.messageId === "string") { + return item.messageId; + } + return item; + }); +}, external_exports.array(external_exports.string())); +var teamStateSchema = external_exports.strictObject({ + id: external_exports.string(), + members: external_exports.array(memberSnapshotSchema), + tasks: external_exports.array(taskSnapshotSchema), + messages: external_exports.array(messageSnapshotSchema), + delivered: deliveredIdsSchema, + nextTaskNumber: external_exports.number().refine((n) => Number.isSafeInteger(n) && n >= 1, { + message: "nextTaskNumber must be a positive safe integer" + }), + failure: external_exports.string().optional() +}); + +// src/domain/task-graph.ts +function validateTaskGraph(tasks) { + const byId = new Map(tasks.map((t2) => [t2.id, t2])); + const live = tasks.filter((t2) => t2.status !== "deleted"); + for (const task of live) { + for (const bid of task.blockedBy) { + if (bid === task.id) { + throw new Error(`team task "${task.id}" cannot block itself`); + } + } + } + for (const task of live) { + const seen = /* @__PURE__ */ new Set(); + for (const bid of task.blockedBy) { + if (seen.has(bid)) { + throw new Error(`team task "${task.id}" repeats blocker "${bid}"`); + } + seen.add(bid); + } + } + for (const task of live) { + for (const bid of task.blockedBy) { + const blocker = byId.get(bid); + if (blocker === void 0 || blocker.status === "deleted") { + throw new Error(`blocker task "${bid}" for "${task.id}" is missing or deleted`); + } + } + } + detectCycle(live, byId); +} +function detectCycle(live, byId) { + const WHITE = 0; + const GRAY = 1; + const BLACK = 2; + const color = /* @__PURE__ */ new Map(); + const visit = (task) => { + color.set(task.id, GRAY); + for (const bid of task.blockedBy) { + const blocker = byId.get(bid); + if (blocker === void 0 || blocker.status === "deleted") continue; + const c = color.get(bid) ?? WHITE; + if (c === GRAY) { + throw new Error(`task dependency cycle includes "${bid}"`); + } + if (c === WHITE) visit(blocker); + } + color.set(task.id, BLACK); + }; + for (const task of live) { + if ((color.get(task.id) ?? WHITE) === WHITE) visit(task); + } +} + +// src/domain/task-view.ts +function taskReady(state, task) { + return task.blockedBy.every((bid) => { + const blocker = state.tasks.find((t2) => t2.id === bid); + return blocker !== void 0 && blocker.status === "completed"; + }); +} +function projectTaskView(state, task) { + const view = { + id: task.id, + revision: task.revision, + subject: task.subject, + description: task.description, + status: task.status, + blockedBy: [...task.blockedBy], + writeScopes: [...task.writeScopes], + ready: task.status === "pending" && taskReady(state, task), + writeScopeWarnings: writeScopeWarnings(state, task) + }; + if (task.ownerId !== void 0) { + const ownerName = task.ownerId === state.id ? "lead" : state.members.find((m) => m.id === task.ownerId)?.name; + if (ownerName !== void 0) view.ownerName = ownerName; + } + return view; +} +function writeScopeWarnings(state, task) { + if (task.status !== "in_progress") return []; + const warnings = /* @__PURE__ */ new Set(); + for (const other of state.tasks) { + if (other.id === task.id || other.status !== "in_progress") continue; + if (scopesOverlap(task.writeScopes, other.writeScopes)) { + warnings.add(`write scopes overlap with ${other.id}`); + } + } + return [...warnings]; +} +function scopesOverlap(left, right) { + for (const l of left) { + for (const r of right) { + if (l === r || l.startsWith(r + "/") || r.startsWith(l + "/")) return true; + } + } + return false; +} + +// src/domain/projection.ts +var TEAM_PROJECTION_STATE_VERSION = 4; +function emptyTeamState(rootId) { + return { + id: rootId, + members: [], + tasks: [], + messages: [], + delivered: [], + nextTaskNumber: 1 + }; +} +function failed(state, failure) { + return { ...state, failure }; +} +function applyProjectionEvent(state, raw) { + if (state.failure !== void 0) return state; + const selected = selectTeamEvent(raw, state.id); + switch (selected.kind) { + case "ignored": + return state; + case "unsupported-version": + return failed(state, `unsupported Agent Teams event version ${String(selected.version)}`); + case "invalid-payload": + return failed(state, `persisted Agent Teams ${selected.type} payload is invalid`); + case "event": + return applyCurrentTeamEvent(state, selected.event); + } +} +function applyCurrentTeamEvent(state, event) { + if (state.failure !== void 0) return state; + switch (event.type) { + case "team/member": + return applyMember(state, event.member); + case "team/task": + return applyTask(state, event.task); + case "team/message/queued": + return applyMessageQueued(state, event.message); + case "team/message/delivered": + return applyMessageDelivered(state, event.messageId, event.targetId); + } +} +function applyMember(state, member) { + const prior = state.members.find((m) => m.id === member.id); + if (prior === void 0) { + if (member.phase !== "provisioning") { + return failed(state, `teammate "${member.name}" must begin provisioning`); + } + if (state.members.some((m) => m.name === member.name)) { + return failed(state, `teammate name "${member.name}" is reused by another member`); + } + return { ...state, members: [...state.members, member] }; + } + if (prior.name !== member.name || prior.provider !== member.provider || prior.context !== member.context) { + return failed(state, `teammate "${prior.id}" changed immutable identity fields`); + } + if (prior.phase !== "provisioning" || member.phase !== "active" && member.phase !== "failed") { + return failed( + state, + `teammate "${member.name}" has an invalid ${prior.phase} -> ${member.phase} transition` + ); + } + return { ...state, members: state.members.map((m) => m.id === member.id ? member : m) }; +} +function applyTask(state, task) { + const prior = state.tasks.find((t2) => t2.id === task.id); + const expectedRevision = prior === void 0 ? 1 : prior.revision + 1; + if (task.revision !== expectedRevision) { + return failed( + state, + prior === void 0 ? `team task "${task.id}" must begin at revision 1` : `team task "${task.id}" revision is not contiguous` + ); + } + const tasks = prior === void 0 ? [...state.tasks, task] : state.tasks.map((t2) => t2.id === task.id ? task : t2); + try { + validateTaskGraph(tasks); + } catch (err) { + return failed(state, err instanceof Error ? err.message : String(err)); + } + let nextTaskNumber = state.nextTaskNumber; + const n = taskNumberFromId(task.id); + if (n !== void 0) { + nextTaskNumber = Math.max(state.nextTaskNumber, Math.min(n + 1, Number.MAX_SAFE_INTEGER)); + } + return { ...state, tasks, nextTaskNumber }; +} +function applyMessageQueued(state, message) { + if (state.messages.some((m) => m.id === message.id)) { + return failed(state, `team message "${message.id}" was queued twice`); + } + return { ...state, messages: [...state.messages, message] }; +} +function applyMessageDelivered(state, messageId, targetId) { + const queued = state.messages.find((m) => m.id === messageId); + if (queued === void 0) { + return failed(state, `team message "${messageId}" was delivered before queueing`); + } + if (queued.targetId !== targetId) { + return failed(state, `team message "${messageId}" target changed`); + } + if (state.delivered.includes(messageId)) { + return failed(state, `team message "${messageId}" was delivered twice`); + } + return { ...state, delivered: [...state.delivered, messageId] }; +} +var viewCache = /* @__PURE__ */ new WeakMap(); +function teamProjectionView(state) { + let byTasks = viewCache.get(state.members); + if (byTasks === void 0) { + byTasks = /* @__PURE__ */ new WeakMap(); + viewCache.set(state.members, byTasks); + } + let entry = byTasks.get(state.tasks); + if (entry === void 0) { + const members = [ + { id: state.id, name: "lead", role: "lead", phase: "active" }, + ...state.members.map((m) => ({ id: m.id, name: m.name, role: "teammate", phase: m.phase, ...m.error !== void 0 ? { error: m.error } : {} })) + ]; + const tasks = state.tasks.filter((t2) => t2.status !== "deleted").map((t2) => projectTaskView(state, t2)); + entry = { healthy: { members, tasks } }; + byTasks.set(state.tasks, entry); + } + if (state.failure === void 0) return entry.healthy; + if (entry.failed === void 0) { + entry.failed = { ...entry.healthy, failure: state.failure }; + } + return entry.failed; +} + +// src/coord/replay.ts +var checkpointDocSchema = external_exports.strictObject({ + kind: external_exports.literal("agent-team-checkpoint"), + stateVersion: external_exports.literal(TEAM_PROJECTION_STATE_VERSION), + lastSeq: external_exports.number().int().nonnegative(), + lastOffset: external_exports.number().int().nonnegative(), + savedAt: external_exports.string(), + state: teamStateSchema, + view: external_exports.unknown() +}); +function checkpointPath(teamDir) { + return path.join(teamDir, "checkpoint.json"); +} +async function load(teamDir, teamId) { + const startedAt = Date.now(); + const eventsFile = path.join(teamDir, "events.jsonl"); + const raw = readBufferOrEmpty(eventsFile); + let checkpointIgnored; + let doc; + try { + const rawDoc = fs.readFileSync(checkpointPath(teamDir), "utf8"); + const parsed = checkpointDocSchema.safeParse(JSON.parse(rawDoc)); + if (!parsed.success) { + checkpointIgnored = `checkpoint invalid: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`; + } else if (parsed.data.state.id !== teamId) { + checkpointIgnored = `checkpoint teamId mismatch (${parsed.data.state.id} != ${teamId})`; + } else { + doc = parsed.data; + } + } catch { + } + const writers = []; + let state = emptyTeamState(teamId); + let seq = 0; + let fromCheckpoint = false; + let corrupt; + if (doc !== void 0) { + const tail = raw.subarray(doc.lastOffset); + const first = firstLineBytes(tail); + if (tail.length > 0 && first === void 0) { + checkpointIgnored = "checkpoint offset desync (tail not line-aligned) \u2014 full replay"; + } else if (first !== void 0 && JSON.parse(first.parsed).seq !== doc.lastSeq + 1) { + checkpointIgnored = "checkpoint offset desync (seq continuity broken) \u2014 full replay"; + } else { + state = doc.state; + seq = doc.lastSeq; + fromCheckpoint = true; + } + } + const startOffset = fromCheckpoint && doc !== void 0 ? doc.lastOffset : 0; + let offset = startOffset; + let consumeRest = true; + while (consumeRest && offset < raw.length) { + const nl = raw.indexOf(10, offset); + if (nl === -1) { + corrupt = { line: seq + 1, reason: "trailing partial line (no newline)" }; + state = withFailure(state, raw.subarray(offset).toString("utf8")); + seq += 1; + consumeRest = false; + break; + } + const lineText = raw.subarray(offset, nl).toString("utf8"); + const lineNo = seq + 1; + offset = nl + 1; + if (lineText.length === 0) { + corrupt = { line: lineNo, reason: "empty line" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + let parsed; + try { + parsed = JSON.parse(lineText); + } catch { + corrupt = { line: lineNo, reason: "invalid JSON" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + const line = parsed; + if (typeof line.writer === "string" && !writers.includes(line.writer)) writers.push(line.writer); + if (typeof parsed !== "object" || parsed === null || typeof parsed.seq !== "number" || !("event" in parsed) || parsed.seq !== lineNo) { + corrupt = { line: lineNo, reason: "line shape invalid or seq discontinuous" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + state = applyProjectionEvent(state, line.event); + seq = lineNo; + if (state.failure !== void 0) { + consumeRest = false; + } + } + return { + state, + view: teamProjectionView(state), + seq, + fromCheckpoint, + checkpointIgnored, + corrupt, + writers, + replayMs: Date.now() - startedAt + }; +} +function readBufferOrEmpty(file) { + try { + return fs.readFileSync(file); + } catch { + return Buffer.alloc(0); + } +} +function firstLineBytes(buf) { + const nl = buf.indexOf(10); + const first = (nl === -1 ? buf : buf.subarray(0, nl)).toString("utf8"); + if (first.length === 0) return void 0; + try { + JSON.parse(first); + return { parsed: first }; + } catch { + return void 0; + } +} +function withFailure(state, rawLine) { + const m = rawLine.match(/"type"\s*:\s*"(team\/[A-Za-z/-]+)"/); + const type = m?.[1] ?? "stream"; + return { ...state, failure: `persisted Agent Teams ${type} payload is invalid` }; +} + +// src/cli/state.ts +function renderState(input, paint) { + const { teamId, loaded, json } = input; + if (json) { + return JSON.stringify( + { + teamId, + seq: loaded.seq, + fromCheckpoint: loaded.fromCheckpoint, + checkpointIgnored: loaded.checkpointIgnored, + corrupt: loaded.corrupt, + writers: loaded.writers, + replayMs: loaded.replayMs, + failure: loaded.state.failure, + view: loaded.view, + mailbox: { + messages: loaded.state.messages, + delivered: loaded.state.delivered + } + }, + null, + 2 + ); + } + const lines = []; + const mode = loaded.fromCheckpoint ? "checkpoint+tail" : "full-replay"; + lines.push( + `${paint.bold(`Agent Team ${teamId}`)} seq ${loaded.seq} ${paint.dim(`${mode} \xB7 ${loaded.replayMs}ms \xB7 writers ${loaded.writers.length}`)}` + ); + if (loaded.corrupt !== void 0) { + lines.push(paint.red(`\u26A0 \u65E5\u5FD7\u635F\u574F fail-closed\uFF08\u884C ${loaded.corrupt.line}\uFF09\uFF1A${loaded.corrupt.reason}`)); + } + if (loaded.state.failure !== void 0) { + lines.push(paint.red(`\u26A0 FAILURE\uFF08\u7EC8\u6001\uFF0C\u540E\u7EED\u5408\u6CD5\u4E8B\u4EF6\u4E0D\u518D\u6539\u53D8\u89C6\u56FE\uFF09\uFF1A${loaded.state.failure}`)); + } + const members = loaded.view.members; + lines.push(""); + lines.push(paint.bold(`Roster (${members.length})`)); + if (members.length === 0) { + lines.push(paint.dim(" \uFF08\u7A7A\uFF09")); + } else { + lines.push(` ${pad("NAME", 16)}${pad("ROLE", 10)}PHASE`); + for (const m of members) { + const row = ` ${pad(m.name, 16)}${pad(m.role, 10)}${m.phase}`; + lines.push(m.error !== void 0 ? paint.red(`${row} \u26A0 ${m.error}`) : row); + } + } + const tasks = loaded.view.tasks; + lines.push(""); + lines.push(paint.bold(`Tasks (${tasks.length})`)); + if (tasks.length === 0) { + lines.push(paint.dim(" \uFF08\u6682\u65E0\u4EFB\u52A1\uFF09")); + } else { + lines.push(` ${pad("ID", 10)}${pad("STATUS", 12)}${pad("OWNER", 12)}${pad("REV", 5)}${pad("READY", 7)}SUBJECT`); + for (const t2 of tasks) { + const owner = t2.ownerName ?? "\u2014"; + const statusCell = pad(t2.status, 12); + const status = t2.status === "completed" ? paint.green(statusCell) : t2.status === "in_progress" ? paint.yellow(statusCell) : statusCell; + lines.push(` ${pad(t2.id, 10)}${status}${pad(owner, 12)}${pad(String(t2.revision), 5)}${pad(String(t2.ready), 7)}${t2.subject}`); + if (t2.blockedBy.length > 0) lines.push(paint.dim(` ${" ".repeat(34)}blockedBy: ${t2.blockedBy.join(", ")}`)); + } + } + const deliveredIds = new Set(loaded.state.delivered); + const pending = loaded.state.messages.filter((m) => !deliveredIds.has(m.id)); + lines.push(""); + lines.push(paint.bold(`Mailbox\uFF08pending ${pending.length} / delivered ${loaded.state.delivered.length}\uFF09`)); + if (loaded.state.messages.length === 0) { + lines.push(paint.dim(" \uFF08\u90AE\u7BB1\u7A7A\u95F2\uFF09")); + } else { + for (const m of loaded.state.messages) { + const state = deliveredIds.has(m.id) ? paint.green("delivered") : paint.yellow("queued"); + lines.push(` ${m.id} ${m.senderName} \u2192 ${targetLabel(loaded, m.targetId)} [${state}]`); + } + } + return lines.join("\n"); +} +function targetLabel(loaded, targetId) { + if (targetId === loaded.state.id) return "lead"; + return loaded.view.members.find((m) => m.id === targetId)?.name ?? targetId; +} +function pad(text, width) { + return text.length >= width ? text + " " : text + " ".repeat(width - text.length); +} + +// src/cli/tail.ts +import fs2 from "node:fs"; +import path2 from "node:path"; +function formatTailLine(input, paint) { + if (input.kind === "invalid") { + return paint.red(`!! \u65E0\u6CD5\u89E3\u6790\u7684\u884C\uFF1A${input.raw.slice(0, 160)}`); + } + const { line } = input; + const time = localTime(line.ts); + const summary = summarize(line); + const type = line.event.type; + const coloredType = type === "team/member" ? paint.cyan(type) : type === "team/task" ? paint.yellow(type) : type === "team/message/queued" || type === "team/message" ? paint.magenta(type) : type === "team/message/delivered" ? paint.green(type) : paint.dim(type); + return `${paint.dim(time)} ${paint.bold(String(line.seq).padStart(4))} ${coloredType} ${summary} ${paint.dim(line.writer)}`; +} +function summarize(line) { + const e = line.event; + if (e.type === "team/member" && e.member !== void 0) { + return `${e.member.name} (${e.member.id}) \u2192 ${e.member.phase}`; + } + if (e.type === "team/task" && e.task !== void 0) { + return `${e.task.id} ${e.task.subject ?? ""} [${e.task.status ?? "?"} r${e.task.revision ?? "?"}]`; + } + if ((e.type === "team/message/queued" || e.type === "team/message") && e.message !== void 0) { + return `${e.message.id} ${e.message.senderName} \u2192 ${e.message.targetId}`; + } + if (e.type === "team/message/delivered") { + return `${e.messageId} \u2192 ${e.targetId}`; + } + return JSON.stringify(e); +} +function localTime(iso) { + const d = new Date(iso); + if (Number.isNaN(d.getTime())) return "invalid-ts"; + const hh = String(d.getHours()).padStart(2, "0"); + const mm = String(d.getMinutes()).padStart(2, "0"); + const ss = String(d.getSeconds()).padStart(2, "0"); + const ms = String(d.getMilliseconds()).padStart(3, "0"); + return `${hh}:${mm}:${ss}.${ms}`; +} +async function followEvents(eventsFile, opts) { + const paint = opts.paint; + const pollMs = opts.pollMs ?? 250; + let offset = 0; + let buffer = ""; + if (!fs2.existsSync(eventsFile)) { + throw new Error(`events file not found: ${eventsFile}`); + } + const history = fs2.readFileSync(eventsFile, "utf8"); + const lines = history.split("\n").filter((l) => l.length > 0); + const start = opts.fromLines !== void 0 ? Math.max(0, lines.length - opts.fromLines) : lines.length; + const emit = (raw) => { + try { + const parsed = JSON.parse(raw); + opts.onLine(formatTailLine({ kind: "line", line: parsed }, paint), { kind: "line", line: parsed }); + } catch { + opts.onLine(formatTailLine({ kind: "invalid", raw }, paint), { kind: "invalid", raw }); + } + }; + for (const raw of lines.slice(start)) { + emit(raw); + } + offset = Buffer.byteLength(history, "utf8"); + for (; ; ) { + if (opts.signal?.aborted) return; + await new Promise((resolve) => setTimeout(resolve, pollMs)); + const stat = fs2.statSync(eventsFile); + if (stat.size < offset) { + offset = 0; + buffer = ""; + } + if (stat.size > offset) { + const slack = 1 << 16; + const chunk = Buffer.alloc(slack); + const fd = fs2.openSync(eventsFile, "r"); + try { + const bytesRead = fs2.readSync(fd, chunk, 0, slack, offset); + if (bytesRead > 0) { + buffer += chunk.toString("utf8", 0, bytesRead); + let nl; + while ((nl = buffer.indexOf("\n")) !== -1) { + const raw = buffer.slice(0, nl); + buffer = buffer.slice(nl + 1); + if (raw.length > 0) emit(raw); + } + offset += bytesRead; + } + } finally { + fs2.closeSync(fd); + } + } + } +} +function eventsFileOf(teamDir) { + return path2.join(teamDir, "events.jsonl"); +} + +// src/cli/inject.ts +import fs3 from "node:fs"; +import path3 from "node:path"; +function injectEvent(teamDir, rawLine, opts = {}) { + const eventsFile = path3.join(teamDir, "events.jsonl"); + fs3.mkdirSync(teamDir, { recursive: true }); + const existing = fs3.existsSync(eventsFile) ? fs3.readFileSync(eventsFile, "utf8") : ""; + const lineCount = existing.length === 0 ? 0 : existing.split("\n").filter((l) => l.length > 0).length; + let parsed; + try { + parsed = JSON.parse(rawLine); + } catch { + throw new Error(`inject-event: \u53C2\u6570\u5FC5\u987B\u662F\u5408\u6CD5 JSON \u884C\uFF0C\u6536\u5230\uFF1A${rawLine.slice(0, 120)}`); + } + const line = JSON.stringify({ + seq: lineCount + 1, + ts: (/* @__PURE__ */ new Date()).toISOString(), + writer: opts.writer ?? "team-ctl:inject", + ...parsed + }); + fs3.appendFileSync(eventsFile, line + "\n", { mode: 384 }); + return { seq: lineCount + 1, line, file: eventsFile }; +} +function invalidMemberSample(teamId) { + return JSON.stringify({ + event: { + type: "team/member", + version: 2, + teamId, + member: { id: "sess-injected-ghost", name: "ghost", description: "injected", provider: "spawn", context: "fresh", phase: "active" } + } + }); +} + +// src/coord/rpc.ts +import net from "node:net"; +import fs5 from "node:fs"; +import path5 from "node:path"; + +// src/coord/paths.ts +import { createHash } from "node:crypto"; +import fs4 from "node:fs"; +import path4 from "node:path"; +import os from "node:os"; +var MAX_SOCKET_PATH = 96; +function resolveSocketPath(teamDir) { + const candidate = path4.join(teamDir, "coordinator.sock"); + if (candidate.length <= MAX_SOCKET_PATH) { + return { socketPath: candidate, fallback: false, registryFile: path4.join(teamDir, "socket.path") }; + } + const hash = createHash("sha256").update(candidate).digest("hex").slice(0, 16); + const tmpRoot = fs4.realpathSync(os.tmpdir()); + const fallbackDir = path4.join(tmpRoot, "agent-team-sockets"); + fs4.mkdirSync(fallbackDir, { recursive: true, mode: 448 }); + try { + fs4.chmodSync(fallbackDir, 448); + } catch { + } + const fallbackPath = path4.join(fallbackDir, `at-${hash}.sock`); + return { socketPath: fallbackPath, fallback: true, registryFile: path4.join(teamDir, "socket.path") }; +} +function discoverSocketPath(teamDir) { + const registryFile = path4.join(teamDir, "socket.path"); + try { + const registered = fs4.readFileSync(registryFile, "utf8").trim(); + if (registered.length > 0) return registered; + } catch { + } + return resolveSocketPath(teamDir).socketPath; +} + +// src/coord/rpc.ts +var COORDINATOR_UNAVAILABLE_MESSAGE = "Agent Teams coordinator is unavailable (between coordinators); retry the request shortly"; +var MAX_RPC_BUFFER_BYTES = 1 << 20; +var RpcClient = class _RpcClient { + constructor(socket, token = void 0, nextId = 1, pending = /* @__PURE__ */ new Map(), maxFrameBytes = MAX_RPC_BUFFER_BYTES) { + this.socket = socket; + this.token = token; + this.nextId = nextId; + this.pending = pending; + this.maxFrameBytes = maxFrameBytes; + } + maxFrameBytes; + static async connect(socketPath, opts = {}) { + const timeoutMs = opts.timeoutMs ?? 3e3; + const socket = await new Promise((resolve, reject) => { + const s = net.connect(socketPath, () => resolve(s)); + s.setEncoding("utf8"); + const timer = setTimeout(() => { + s.destroy(); + reject(new Error(`rpc connect timeout after ${timeoutMs}ms: ${socketPath}`)); + }, timeoutMs); + s.once("error", (err) => { + clearTimeout(timer); + reject(err); + }); + resolveSocketOnConnect(s, () => clearTimeout(timer)); + }); + const client = new _RpcClient(socket, opts.token, 1, /* @__PURE__ */ new Map(), opts.maxFrameBytes); + socket.on("data", (chunk) => client.onData(chunk)); + socket.on("close", () => client.failAll(new Error("rpc connection closed"))); + socket.on("error", (err) => client.failAll(err)); + return client; + } + async call(method, params, opts = {}) { + const id = this.nextId++; + const timeoutMs = opts.timeoutMs ?? 15e3; + if (opts.signal?.aborted) { + return Promise.reject( + new TeamError("TEAM_WAIT_ABORTED", `wait_agent aborted: ${abortReasonText(opts.signal.reason)}`) + ); + } + const payload = JSON.stringify({ id, method, params, ...this.token !== void 0 ? { token: this.token } : {} }) + "\n"; + return new Promise((resolve, reject) => { + let settled = false; + let timer; + const finish = (fn) => { + if (settled) return; + settled = true; + clearTimeout(timer); + opts.signal?.removeEventListener("abort", onAbort); + this.pending.delete(id); + fn(); + }; + const onAbort = () => { + finish( + () => reject(new TeamError("TEAM_WAIT_ABORTED", `wait_agent aborted: ${abortReasonText(opts.signal?.reason)}`)) + ); + this.socket.destroy(); + }; + timer = setTimeout(() => { + finish(() => reject(new Error(`rpc call ${method} timed out after ${timeoutMs}ms`))); + }, timeoutMs); + this.pending.set(id, { + resolve: (v) => finish(() => resolve(v)), + reject: (e) => finish(() => reject(e)) + }); + opts.signal?.addEventListener("abort", onAbort, { once: true }); + this.socket.write(payload, (err) => { + if (err) finish(() => reject(err)); + }); + }); + } + close() { + this.socket.destroy(); + } + onData(chunk) { + this.buffer += chunk; + if (Buffer.byteLength(this.buffer, "utf8") > this.maxFrameBytes) { + this.failAll(new Error(`rpc response frame exceeds ${this.maxFrameBytes} bytes`)); + this.socket.destroy(); + return; + } + let nl; + while ((nl = this.buffer.indexOf("\n")) !== -1) { + const line = this.buffer.slice(0, nl); + this.buffer = this.buffer.slice(nl + 1); + if (line.trim().length === 0) continue; + try { + this.onResponse(JSON.parse(line)); + } catch { + this.failAll(new Error("invalid rpc response frame")); + } + } + } + buffer = ""; + onResponse(res) { + const entry = this.pending.get(res.id); + if (entry === void 0) return; + this.pending.delete(res.id); + if (res.ok) { + entry.resolve(res.result); + } else if (res.error?.code !== void 0) { + entry.reject(new TeamError(res.error.code, res.error.message)); + } else { + const err = new Error(res.error?.message ?? "rpc error"); + if (res.error?.name) err.name = res.error.name; + entry.reject(err); + } + } + failAll(err) { + for (const [, entry] of this.pending) entry.reject(err); + this.pending.clear(); + } +}; +function resolveSocketOnConnect(socket, onConnected) { + socket.once("connect", onConnected); +} +function rpcTokenPath(teamDir) { + return path5.join(teamDir, "rpc.token"); +} +function readRpcToken(teamDir) { + try { + const token = fs5.readFileSync(rpcTokenPath(teamDir), "utf8").trim(); + return token.length > 0 ? token : void 0; + } catch { + return void 0; + } +} +function coordinatorUnavailableError(detail) { + return new TeamError("TEAM_DISPOSED", COORDINATOR_UNAVAILABLE_MESSAGE, { cause: detail }); +} +function abortReasonText(reason) { + if (reason instanceof Error) return reason.message; + if (reason === void 0 || reason === null) return "aborted"; + return String(reason); +} +async function callCoordinator(teamDir, teamId, method, params, opts = {}) { + const socketPath = discoverSocketPath(teamDir); + const token = readRpcToken(teamDir); + const client = await RpcClient.connect(socketPath, { + timeoutMs: opts.connectTimeoutMs ?? 1e3, + ...token !== void 0 ? { token } : {} + }).catch((err) => { + throw coordinatorUnavailableError(`socket ${socketPath}: ${err.code ?? err.message}`); + }); + try { + return await client.call(method, params, { + timeoutMs: opts.timeoutMs, + ...opts.signal !== void 0 ? { signal: opts.signal } : {} + }); + } finally { + client.close(); + } +} + +// src/cli/call.ts +async function callTeam(teamDir, method, paramsJson) { + let params = {}; + if (paramsJson !== void 0 && paramsJson.trim().length > 0) { + try { + params = JSON.parse(paramsJson); + } catch (err) { + return { + ok: false, + output: `call: params \u4E0D\u662F\u5408\u6CD5 JSON\uFF08${err instanceof Error ? err.message : String(err)}\uFF09`, + audit: JSON.stringify({ tool: "team-ctl", action: "call", teamDir, method, ok: false, reason: "bad-params" }) + }; + } + } + try { + const result = await callCoordinator(teamDir, "", method, params, { timeoutMs: 1e4 }); + return { + ok: true, + output: JSON.stringify(result, null, 2), + audit: JSON.stringify({ tool: "team-ctl", action: "call", teamDir, method, ok: true }) + }; + } catch (err) { + const summary = err instanceof TeamError ? `[${err.code}] ${err.message}` : err instanceof Error && err.message === COORDINATOR_UNAVAILABLE_MESSAGE ? COORDINATOR_UNAVAILABLE_MESSAGE : err instanceof Error ? err.message.split("\n")[0] : String(err); + return { + ok: false, + output: `call ${method} \u5931\u8D25\uFF1A${summary}`, + audit: JSON.stringify({ + tool: "team-ctl", + action: "call", + teamDir, + method, + ok: false, + code: err instanceof TeamError ? err.code : void 0 + }) + }; + } +} + +// src/cli/colors.ts +function paintFor(stream) { + const enabled = process.env.FORCE_COLOR === "1" || stream.isTTY === true && process.env.NO_COLOR === void 0; + const wrap = (code) => (text) => enabled ? `\x1B[${code}m${text}\x1B[0m` : text; + return { + enabled, + cyan: wrap("36"), + yellow: wrap("33"), + magenta: wrap("35"), + green: wrap("32"), + red: wrap("31"), + bold: wrap("1"), + dim: wrap("2") + }; +} +function paintForStream(stream) { + return paintFor({ isTTY: stream.isTTY }); +} + +// src/cli/ui.ts +import fs9 from "node:fs"; +import path10 from "node:path"; + +// src/provider/transcript.ts +import fs6 from "node:fs"; +import os2 from "node:os"; +import path6 from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +// src/provider/model-selection.ts +function parseModelSelection(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0; + const record = value; + const providerId = nonEmptyString(record.providerId); + const modelId = nonEmptyString(record.modelId); + if (providerId === void 0 || modelId === void 0) return void 0; + const options = record.options; + if (options !== void 0 && (typeof options !== "object" || options === null || Array.isArray(options))) { + return void 0; + } + let reasoningLevel; + const rawLevel = options !== void 0 ? options.reasoningLevel : record.reasoningLevel; + if (rawLevel !== void 0) { + reasoningLevel = nonEmptyString(rawLevel); + if (reasoningLevel === void 0) return void 0; + } + return { providerId, modelId, ...reasoningLevel !== void 0 ? { reasoningLevel } : {} }; +} +function nonEmptyString(value) { + if (typeof value !== "string") return void 0; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : void 0; +} + +// src/provider/transcript.ts +function defaultDbPath() { + return process.env.TEAM_DB_PATH ?? path6.join(os2.homedir(), ".zcode", "cli", "db", "db.sqlite"); +} +var TranscriptReader = class { + dbPath; + db = null; + dbMissing = false; + constructor(deps = {}) { + this.dbPath = deps.dbPath ?? defaultDbPath(); + } + get path() { + return this.dbPath; + } + /** 库不存在 = 空库语义(探针方法走缺省值,不建临时库)。 */ + missing() { + if (!this.dbMissing) this.dbMissing = !fs6.existsSync(this.dbPath); + else if (!fs6.existsSync(this.dbPath)) return true; + else this.dbMissing = false; + return this.dbMissing; + } + open() { + if (this.db !== null) return this.db; + if (!fs6.existsSync(this.dbPath)) { + throw new Error("transcript db missing"); + } + this.db = new DatabaseSync(this.dbPath, { readOnly: true }); + return this.db; + } + close() { + this.db?.close(); + this.db = null; + } + /** 会话行实查;不存在 → undefined;读失败 → 抛错。 */ + session(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + "SELECT id, parent_id, directory, task_type, title, time_created FROM session WHERE id = ?" + ).get(sessionId); + return row ?? void 0; + } + /** 找「目录 = cwd 且创建于 sinceMs 之后、首条真实用户文本 = firstPrompt」的会话(fresh spawn 探针)。 */ + findSessionByFirstPrompt(args) { + if (this.missing()) return void 0; + const rows = this.open().prepare( + "SELECT id, time_created FROM session WHERE directory = ? AND time_created >= ? ORDER BY time_created ASC" + ).all(args.cwd, args.sinceMs - 2e3); + for (const row of rows) { + if (args.excludeSessionIds?.has(row.id)) continue; + const first = this.firstRealUserText(row.id); + if (first === args.firstPrompt) return row.id; + } + return void 0; + } + /** 首条「真实用户」消息的文本部分(跳过 hook/系统注入的 model-only 消息)。 */ + firstRealUserText(sessionId) { + if (this.missing()) return null; + const rows = this.open().prepare( + `SELECT p.data pdata FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + ORDER BY m.sequence, p.sequence LIMIT 1` + ).all(sessionId); + if (rows.length === 0) return null; + return extractText(rows[0].pdata); + } + /** 会话中是否已存在该文本的「真实用户」消息(delivered/去重探针:prompt 逐字落库)。 */ + hasUserText(sessionId, text) { + if (this.missing()) return false; + const row = this.open().prepare( + `SELECT COUNT(*) n FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + AND json_extract(p.data,'$.text') = ? LIMIT 1` + ).get(sessionId, text); + return row.n > 0; + } + /** 会话全部「真实用户」文本消息(时间序;轮次 prompt 审计/恰一次检索用)。 */ + realUserTexts(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.id mid, m.time_created tc, p.data pdata, + json_extract(m.data,'$.semantics.origin') origin, + json_extract(m.data,'$.modelSelection.modelId') model + FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + return rows.map((r) => ({ + messageId: r.mid, + text: extractText(r.pdata) ?? "", + timeCreated: r.tc, + origin: r.origin, + modelId: r.model + })); + } + /** 会话最新使用的模型(成员行 model 字段实查;无消息 → undefined)。 */ + latestModel(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT json_extract(m.data,'$.modelSelection.modelId') model FROM message m + WHERE m.session_id = ? AND json_extract(m.data,'$.modelSelection.modelId') IS NOT NULL + ORDER BY m.sequence DESC LIMIT 1` + ).get(sessionId); + return row?.model; + } + /** + * 最近一条「真实用户提交」(semantics.origin=real_user)消息携带的模型快照 + 提交时间。 + * 0.4.0 三源判定的「提交证据」:宿主保存用户消息时写入该次提交的 modelSelection(本机源码核对), + * 输入框切换在提交瞬间即体现在这里——不依赖会话选模条目(issue #7 场景它可能滞后)。 + * hook/系统注入的 user 消息(origin≠real_user)不算提交。 + */ + latestSubmissionSelection(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT m.time_created tc, + json_extract(m.data,'$.modelSelection.providerId') p, + json_extract(m.data,'$.modelSelection.modelId') mo, + json_extract(m.data,'$.modelSelection.options.reasoningLevel') lvl + FROM message m + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(m.data,'$.modelSelection.providerId') IS NOT NULL + AND json_extract(m.data,'$.modelSelection.modelId') IS NOT NULL + ORDER BY m.time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.p.trim(); + const modelId = row.mo.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const lvl = typeof row.lvl === "string" ? row.lvl.trim() : ""; + return { + selection: { providerId, modelId, ...lvl.length > 0 ? { reasoningLevel: lvl } : {} }, + at: row.tc + }; + } + /** 会话选模条目 + 生效时间(UPSERT 单行;用于与提交快照比较「后来是否有 /model 修改」)。 */ + latestModelSelectionTimed(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT data, MAX(COALESCE(time_updated, time_created), time_created) at FROM session_entry + WHERE session_id = ? AND type = 'runtime/model_selection' + ORDER BY time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const selection = this.latestModelSelection(sessionId); + if (selection === void 0) return void 0; + return { selection, at: row.at }; + } + /** + * 最近一次**主轮**实际模型调用(+ 开始时间)。query_source='main_turn' 过滤是 0.4.0 关键口径: + * compact/标题生成/goal 摘要/subagent/workflow 子轮的行属于辅助模型,绝不能当作 Lead 当前模型 + * (实测本机取值域 = compact, goal_summary_title, main_turn, session_title, subagent, + * target_completion_verification, workflow_child)。 + */ + latestMainTurnUsage(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT provider_id, model_id, variant, started_at FROM model_usage + WHERE session_id = ? AND query_source = 'main_turn' + ORDER BY started_at DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.provider_id.trim(); + const modelId = row.model_id.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const variant = typeof row.variant === "string" ? row.variant.trim() : ""; + return { + selection: { providerId, modelId, ...variant.length > 0 ? { reasoningLevel: variant } : {} }, + at: row.started_at + }; + } + /** + * 会话库中最近一次 setModel 的选择(Round A 实证:条目为 UPSERT 单行,canonical id + * `:runtime-model-selection`,时间排序安全)。data 取嵌套 modelSelection 优先; + * 兼容旧行把 providerId/modelId/thoughtLevel 平铺在顶层的形态。 + */ + latestModelSelection(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT data FROM session_entry + WHERE session_id = ? AND type = 'runtime/model_selection' + ORDER BY time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const data = parseOrNull(row.data); + if (data === null) return void 0; + const nested = parseModelSelection(data.modelSelection); + if (nested !== void 0) return nested; + const providerId = typeof data.providerId === "string" ? data.providerId.trim() : ""; + const modelId = typeof data.modelId === "string" ? data.modelId.trim() : ""; + if (providerId.length === 0 || modelId.length === 0) return void 0; + const thoughtLevel = typeof data.thoughtLevel === "string" ? data.thoughtLevel.trim() : ""; + return { + providerId, + modelId, + ...thoughtLevel.length > 0 ? { reasoningLevel: thoughtLevel } : {} + }; + } + /** 最近一次真实模型调用(session_entry 缺失时的继承兜底;variant = 思考强度)。 */ + latestModelUsage(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT provider_id, model_id, variant FROM model_usage + WHERE session_id = ? ORDER BY started_at DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.provider_id.trim(); + const modelId = row.model_id.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const variant = typeof row.variant === "string" ? row.variant.trim() : ""; + return { + providerId, + modelId, + ...variant.length > 0 ? { reasoningLevel: variant } : {} + }; + } + /** 完成回合导出(D3 fork 转录):真实用户消息 + 助手文本;tool 部分记工具名。 */ + exportTurns(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.data mdata, p.data pdata FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + const turns = []; + for (const r of rows) { + const message = parseOrNull(r.mdata); + const part = parseOrNull(r.pdata); + if (message === null || part === null) continue; + const isUser = message.role === "user"; + const isAssistant = message.role === "assistant"; + const realUser = isUser && message.semantics?.origin === "real_user"; + if (part.type === "text" && typeof part.text === "string") { + if (realUser) turns.push({ role: "user", text: part.text, toolNames: [] }); + else if (isAssistant) turns.push({ role: "assistant", text: part.text, toolNames: [] }); + } else if (isAssistant && part.type === "tool" && typeof part.tool === "string") { + const last = turns[turns.length - 1]; + if (last !== void 0 && last.role === "assistant" && !last.toolNames.length) { + last.toolNames.push(part.tool); + } else { + turns.push({ role: "assistant", text: "", toolNames: [part.tool] }); + } + } + } + return turns; + } + /** + * T5.7 成员会话查看视图导出(detail 合成数据源;只读、走 session_id 索引): + * 时间序全量 part 行(text/tool 两型;其余 part 型跳过),损坏行跳过。 + * 与 exportTurns 的区别:保留每条 part 的时间戳/role/工具状态(面板折叠行渲染), + * 不做回合聚合;hook 注入文本不落 transcript part(H14),framed 徽标由 + * panel/detail.ts 以 events 回填(不改写原文)。 + */ + exportDetailParts(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.data mdata, m.time_created mtc, p.data pdata, p.time_created ptc + FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + const out = []; + for (const r of rows) { + const message = parseOrNull(r.mdata); + const part = parseOrNull(r.pdata); + if (message === null || part === null) continue; + const role = message.role === "user" ? "user" : message.role === "assistant" ? "assistant" : void 0; + if (role === void 0) continue; + if (role === "user" && message.semantics?.origin !== "real_user") continue; + const ts2 = typeof r.ptc === "number" ? r.ptc : r.mtc; + if (part.type === "text" && typeof part.text === "string") { + out.push({ ts: ts2, role, kind: "text", text: part.text }); + } else if (part.type === "tool" && typeof part.tool === "string") { + const status = typeof part.state?.status === "string" ? part.state.status : "unknown"; + out.push({ + ts: ts2, + role: "assistant", + kind: "toolCall", + toolName: part.tool, + toolStatus: status, + ...part.state?.input !== void 0 ? { toolInput: part.state.input } : {}, + ...part.state?.output !== void 0 ? { toolOutput: part.state.output } : {} + }); + } + } + return out; + } +}; +function parseOrNull(raw) { + try { + return JSON.parse(raw); + } catch { + return null; + } +} +function extractText(partData) { + try { + const part = JSON.parse(partData); + return typeof part.text === "string" ? part.text : null; + } catch { + return null; + } +} + +// src/panel/detail.ts +var DETAIL_DEFAULT_LIMIT = 100; +var DETAIL_MAX_LIMIT = 200; +var DETAIL_PAGE_BYTES = 256 * 1024; +var TOOL_PAYLOAD_CHARS = 2e3; +var SessionNotSettledError = class extends TeamError { + sessionNotSettled = true; +}; +function resolveMemberSessionId(deps, target, readOriginSession) { + if (target === deps.teamId || target === "lead") { + return { memberId: deps.teamId, sessionId: deps.teamId, name: "lead" }; + } + const member = deps.state.members.find((m) => m.id === target || m.name === target); + if (member === void 0) { + throw new TeamError("TEAM_MEMBER_NOT_FOUND", `active teammate "${target}" not found`); + } + const sessionId = readOriginSession(member.id); + if (sessionId === null || sessionId === void 0) { + throw new SessionNotSettledError( + "TEAM_MEMBER_NOT_FOUND", + `active teammate "${member.name}" not found` + ); + } + return { memberId: member.id, sessionId, name: member.name }; +} +function synthesizeDetailStream(deps, sessionId, memberId) { + const rows = deps.reader.exportDetailParts(sessionId); + const framedQueue = framedFor(deps.state, memberId); + const items = []; + const used = /* @__PURE__ */ new Set(); + for (const row of rows) { + const item = toItem(row); + if (item.role === "user" && item.kind === "text" && item.text !== void 0) { + const idx = framedQueue.findIndex((f, i) => !used.has(i) && textCarriesFrame(item.text, f)); + if (idx >= 0) { + used.add(idx); + item.framed = { messageId: framedQueue[idx].messageId, from: framedQueue[idx].from }; + } + } + items.push(item); + } + return { items }; +} +function framedFor(state, memberId) { + const delivered = new Set(state.delivered); + return state.messages.filter((m) => m.targetId === memberId && delivered.has(m.id)).map((m) => ({ + messageId: m.id, + from: m.senderName, + body: m.content.map((b) => b.type === "text" ? b.text : JSON.stringify(b)).join("\n") + })); +} +function textCarriesFrame(text, framed) { + if (text.includes(`Team message from ${framed.from}:`)) return true; + const anchor = framed.body.slice(0, 64); + return anchor.length >= 8 && text.includes(anchor); +} +function toItem(row) { + const base = { ts: new Date(row.ts).toISOString(), role: row.role }; + if (row.kind === "text") { + return { ...base, kind: "text", text: row.text ?? "" }; + } + const tool = { name: row.toolName ?? "unknown", status: row.toolStatus ?? "unknown" }; + const parts = []; + if (row.toolInput !== void 0) parts.push(`input: ${stringify(row.toolInput)}`); + if (row.toolOutput !== void 0) parts.push(`output: ${stringify(row.toolOutput)}`); + if (parts.length === 0) return { ...base, kind: "toolCall", tool }; + const payload = parts.join("\n"); + return { + ...base, + kind: "toolCall", + tool, + text: payload.length > TOOL_PAYLOAD_CHARS ? payload.slice(0, TOOL_PAYLOAD_CHARS) + "\n\u2026(truncated)" : payload + }; +} +function stringify(v) { + if (typeof v === "string") return v; + try { + return JSON.stringify(v); + } catch { + return String(v); + } +} +function projectSummary(items) { + const out = []; + let round = { tools: [] }; + for (const item of items) { + if (item.role === "user" && item.kind === "text") { + flushRound(out, round); + round = { user: item, tools: [] }; + continue; + } + if (item.kind === "toolCall") { + round.tools.push(item); + continue; + } + if (item.role === "assistant" && item.kind === "text" && (item.text ?? "").trim().length > 0) { + round.conclusion = item; + } + } + flushRound(out, round); + return out; +} +function flushRound(out, round) { + if (round.user !== void 0) out.push(round.user); + if (round.tools.length > 0) out.push(toolGroupItem(round.tools)); + if (round.conclusion !== void 0) out.push(round.conclusion); +} +function toolGroupItem(tools) { + const entries = tools.map((item) => ({ + ts: item.ts, + name: item.tool?.name ?? "unknown", + status: item.tool?.status ?? "unknown", + ...item.text !== void 0 ? { text: item.text } : {} + })); + const last = entries[entries.length - 1]; + return { ts: last.ts, role: "assistant", kind: "toolGroup", count: entries.length, tools: entries }; +} +function pageDetail(items, opts) { + const limit = normalizeLimit(opts.limit); + const total = items.length; + const upper = opts.cursor !== void 0 ? Math.min(opts.cursor - 1, total) : total; + const start = Math.max(0, upper - limit); + let slice = items.slice(start, upper); + let truncated = false; + const bytesOf = (value) => new TextEncoder().encode(JSON.stringify(value)).length; + let bytes = bytesOf(slice); + while (slice.length > 1 && bytes > DETAIL_PAGE_BYTES) { + slice = slice.slice(1); + truncated = true; + bytes = bytesOf(slice); + } + const firstSeq = start + (items.slice(start, upper).length - slice.length) + 1; + const numbered = slice.map((item, i) => ({ seq: firstSeq + i, ...item })); + const page = { items: numbered }; + if (start > 0) page.nextCursor = firstSeq; + return { page, total, truncated }; +} +function normalizeLimit(limit) { + if (limit === void 0) return DETAIL_DEFAULT_LIMIT; + if (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1) { + throw new TeamError("TEAM_INVALID_ARGUMENT", "limit must be a positive safe integer"); + } + return Math.min(limit, DETAIL_MAX_LIMIT); +} +function buildDetail(deps, args, readOriginSession) { + const { memberId, sessionId } = resolveMemberSessionId(deps, args.target, readOriginSession); + const stream = synthesizeDetailStream(deps, sessionId, memberId); + const sourceTotal = stream.items.length; + const projected = projectSummary(stream.items); + const { page, total, truncated } = pageDetail(projected, { + ...args.cursor !== void 0 ? { cursor: args.cursor } : {}, + ...args.limit !== void 0 ? { limit: args.limit } : {} + }); + return { + sessionId, + memberId, + page, + ...truncated ? { truncated: true } : {}, + total, + sourceTotal + }; +} +function renderDetailText(result, memberName) { + const lines = []; + lines.push( + `member ${memberName} (${result.memberId}) \xB7 session ${result.sessionId} \xB7 ${result.total} items (summary of ${result.sourceTotal})` + ); + for (const item of result.page.items) { + const time = item.ts.slice(11, 19); + if (item.kind === "toolCall") { + lines.push(`[${time}] ${item.role} tool ${item.tool?.name ?? "?"} (${item.tool?.status ?? "?"})`); + if (item.text !== void 0) { + for (const l of item.text.split("\n").slice(0, 6)) lines.push(` ${l.slice(0, 160)}`); + } + continue; + } + if (item.kind === "toolGroup") { + const counts = /* @__PURE__ */ new Map(); + for (const tool of item.tools ?? []) counts.set(tool.name, (counts.get(tool.name) ?? 0) + 1); + const list = [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([name, n]) => `${name}\xD7${n}`).join(" \xB7 "); + lines.push(`[${time}] ${item.role} \xB7 ${item.count ?? item.tools?.length ?? 0} \u4E2A\u52A8\u4F5C\uFF08${list}\uFF09`); + continue; + } + const badge = item.framed !== void 0 ? ` [team \u2190 ${item.framed.from}]` : ""; + lines.push(`[${time}] ${item.role}${badge}:`); + for (const l of (item.text ?? "").split("\n")) lines.push(` ${l}`); + } + if (result.truncated === true) lines.push(`(page truncated to ${DETAIL_PAGE_BYTES / 1024}KiB budget)`); + if (result.page.nextCursor !== void 0) lines.push(`(earlier messages: cursor=${result.page.nextCursor})`); + return lines.join("\n"); +} + +// src/provider/member-files.ts +import fs7 from "node:fs"; +import path7 from "node:path"; +function memberPaths(teamDir, memberId) { + const memberDir = path7.join(teamDir, "members", memberId); + const runDir = path7.join(memberDir, "run"); + return { + memberDir, + originFile: path7.join(memberDir, "origin.json"), + receiptsFile: path7.join(memberDir, "receipts.jsonl"), + stopBudgetFile: path7.join(memberDir, "stop-budget.json"), + runDir, + currentFile: path7.join(runDir, "current.json"), + drainMarkerFile: path7.join(runDir, "drain-requested.json"), + modelFailedFile: path7.join(memberDir, "model-failed.json") + }; +} +function readJson(file) { + let raw; + try { + raw = fs7.readFileSync(file, "utf8"); + } catch (err) { + if (err.code === "ENOENT") return void 0; + throw err; + } + return JSON.parse(raw); +} +function readOrigin(paths) { + return readJson(paths.originFile); +} + +// src/mcp/identity.ts +import fs8 from "node:fs"; +import path9 from "node:path"; + +// src/shared.ts +import path8 from "node:path"; +import os3 from "node:os"; +function dataDir() { + const candidates = [ + process.env.TEAM_PLUGIN_DATA, + process.env.ZCODE_PLUGIN_DATA, + process.env.CLAUDE_PLUGIN_DATA + ]; + for (const c of candidates) if (c && c.trim()) return c; + return path8.join(os3.homedir(), ".zcode", "agent-team-dev-data"); +} + +// src/mcp/identity.ts +function sessionMapPath(dataRoot) { + return path9.join(dataRoot, "session-map.json"); +} +function readSessionRegistry(dataRoot) { + try { + const parsed = JSON.parse(fs8.readFileSync(sessionMapPath(dataRoot), "utf8")); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return parsed; + } catch { + return {}; + } +} + +// src/ui-core/view.ts +var VIEW_STATE_VERSION = 4; + +// src/panel/view-service.ts +function resolveMemberSession(teamDir, dataRoot, memberId) { + const origin = readOrigin(memberPaths(teamDir, memberId))?.sessionId; + if (origin !== null && origin !== void 0) return origin; + for (const entry of Object.values(readSessionRegistry(dataRoot))) { + if (entry.memberId === memberId && typeof entry.session_id === "string") return entry.session_id; + } + return void 0; +} +function buildStaticFrame(loaded, teamId, generatedAt, sessionId, teamDir, dataRoot) { + const state = loaded.state; + const members = [ + { target: "lead", role: "lead", status: "inactive", diagnostics: [], id: teamId, sessionId: teamId } + ]; + for (const m of state.members) { + const memberSessionId = teamDir !== void 0 && dataRoot !== void 0 ? resolveMemberSession(teamDir, dataRoot, m.id) : void 0; + members.push({ + target: m.name, + role: "teammate", + status: m.phase === "failed" ? "failed" : m.phase === "provisioning" ? "provisioning" : "inactive", + description: m.description, + provider: m.provider, + context: m.context, + diagnostics: m.error !== void 0 ? [m.error] : [], + id: m.id, + ...memberSessionId !== void 0 ? { sessionId: memberSessionId } : {} + }); + } + return { + type: "view", + stateVersion: VIEW_STATE_VERSION, + team: { + teamId, + status: state.failure !== void 0 ? "failure" : "active", + ...state.failure !== void 0 ? { failure: state.failure } : {}, + seq: loaded.seq + }, + members, + tasks: loaded.view.tasks, + meta: { + generatedAt, + revision: loaded.seq, + ...sessionId !== void 0 ? { sessionId } : {} + } + }; +} + +// src/ui-core/tokens.ts +var TOKEN_CSS = ` +:root, [data-theme="light"] { + color-scheme: light; + /* \u6587\u5B57\u56DB\u6863\uFF08dsw label-primary/secondary/tertiary/caption\uFF1B + caption \u65E0\u72EC\u7ACB\u5BBF\u4E3B\u53D8\u91CF \u2192 tertiary \u540C\u6863 + \u5B57\u9762\u515C\u5E95\u533A\u5206\uFF09 */ + --at-label-primary: var(--color-text-primary, var(--foreground, #1a2233)); + --at-label-secondary: var(--color-text-secondary, var(--muted-foreground, #3d4a5c)); + --at-label-tertiary: var(--color-text-tertiary, var(--muted-foreground, #8a94a6)); + --at-label-caption: var(--color-text-tertiary, #9aa3b2); + /* \u80CC\u666F\u4E24\u6863\uFF08dsw specific-menu / bg-layer-2\uFF09 */ + --at-bg-menu: var(--color-background-secondary, var(--muted, #f7f8fa)); + --at-bg-layer-2: var(--color-background-primary, var(--card, #ffffff)); + /* \u63CF\u8FB9\u4E09\u6863\uFF08dsw border-l1/l2/l3\uFF1B\u5BBF\u4E3B\u5355\u6863 --border \u2192 \u4E09\u6863\u900F\u660E\u5EA6\u6D3E\u751F\uFF09 */ + --at-border-l1: var(--color-border-primary, var(--border, rgba(16, 24, 40, 0.08))); + --at-border-l2: var(--color-border-tertiary, var(--border, #e3e6eb)); + --at-border-l3: var(--color-border-secondary, var(--border, #c9cfd8)); + /* \u72B6\u6001\u70B9\u4E94\u7C7B\u8272\uFF08ongoing/idle/done/warning \u2192 --green/\u7070/--blue/--yellow \u6216\u81EA\u7ED8\uFF09 */ + --at-state-ongoing: var(--color-text-success, var(--green, #12a675)); + --at-state-error: var(--color-text-danger, var(--red, #e5484d)); + --at-state-idle: var(--color-text-disabled, #98a2b3); + --at-state-warning: var(--color-text-warning, var(--yellow, #f59e0b)); + --at-state-done: var(--color-text-info, var(--blue, #3e7bfa)); + /* \u4E1A\u52A1\u4E3B\u8272\uFF08dsw state-business-primary\uFF1A\u5F53\u524D\u4F1A\u8BDD\u9AD8\u4EAE/info Tag\uFF09 */ + --at-business: var(--color-text-info, var(--primary, #3e7bfa)); + /* \u9519\u8BEF\u6587\u672C\uFF08dsw state-error-primary\uFF09 */ + --at-error-text: var(--color-text-danger, var(--red, var(--destructive, #d93036))); + /* advisory \u8B66\u544A\u6587\u672C\u8272\uFF08\u6DF1\u7425\u73C0\u4FDD\u8BC1 11px \u5C0F\u5B57\u5BF9\u6BD4\u5EA6\uFF09 */ + --at-warning-text: var(--color-text-warning, var(--yellow, #b45309)); + /* \u9634\u5F71\u4E24\u6863\uFF08dsw elevation-prominent / elevation-panel\uFF09 */ + --at-shadow-prominent: var(--shadow-lg, 0 8px 28px rgba(16, 24, 40, 0.16)); + --at-shadow-panel: var(--shadow-md, 0 4px 16px rgba(16, 24, 40, 0.12)); + /* \u6EDA\u52A8\u6761\uFF08dsh scrollbar \u4EE4\u724C\u81EA\u7ED8\uFF09 */ + --at-scrollbar-thumb: color-mix(in srgb, var(--at-label-tertiary) 40%, transparent); + --at-scrollbar-thumb-hover: color-mix(in srgb, var(--at-label-tertiary) 60%, transparent); + /* \u5B57\u4F53\uFF08\u4E0D\u5F15\u5916\u90E8\u5B57\u4F53\uFF0C\u8DDF\u968F\u5BBF\u4E3B UI \u5B57\u4F53\u6808\uFF09 */ + --at-font: var(--font-sans, -apple-system, "PingFang SC", "Segoe UI", sans-serif); +} +[data-theme="dark"] { + color-scheme: dark; + --at-label-primary: var(--color-text-primary, var(--foreground, #e8eaf0)); + --at-label-secondary: var(--color-text-secondary, var(--muted-foreground, #c0c6d2)); + --at-label-tertiary: var(--color-text-tertiary, var(--muted-foreground, #8d95a3)); + --at-label-caption: var(--color-text-tertiary, #7d8593); + --at-bg-menu: var(--color-background-secondary, var(--muted, #1b1e24)); + --at-bg-layer-2: var(--color-background-primary, var(--card, #23262d)); + --at-border-l1: var(--color-border-primary, var(--border, rgba(255, 255, 255, 0.08))); + --at-border-l2: var(--color-border-tertiary, var(--border, #333842)); + --at-border-l3: var(--color-border-secondary, var(--border, #434a56)); + --at-state-ongoing: var(--color-text-success, var(--green, #2fbf8f)); + --at-state-error: var(--color-text-danger, var(--red, #ff6b6e)); + --at-state-idle: var(--color-text-disabled, #7d8593); + --at-state-warning: var(--color-text-warning, var(--yellow, #ffb454)); + --at-state-done: var(--color-text-info, var(--blue, #6c9cff)); + --at-business: var(--color-text-info, var(--primary, #6c9cff)); + --at-error-text: var(--color-text-danger, var(--red, var(--destructive, #ff8a8d))); + /* advisory \u8B66\u544A\u6587\u672C\u8272 */ + --at-warning-text: var(--color-text-warning, var(--yellow, #ffb454)); + --at-shadow-prominent: var(--shadow-lg, 0 8px 28px rgba(0, 0, 0, 0.5)); + --at-shadow-panel: var(--shadow-md, 0 4px 16px rgba(0, 0, 0, 0.4)); +} +`; + +// src/ui-core/css.ts +var COMPONENT_CSS = ` +${TOKEN_CSS} +* { box-sizing: border-box; } +.at-root { + font-family: var(--at-font); + font-size: 13px; + line-height: 1.5; + color: var(--at-label-primary); + width: 100%; +} +/* \xA710.3 \u9762\u677F\uFF1A\u5BBD min(500px, \u5BB9\u5668\u221232px)\uFF1B\u7D27\u51D1 min(320px,\u2026)\uFF1B\u6700\u5927\u9AD8 min(680px, \u89C6\u53E3\u221232px)\uFF1B + \u5706\u89D2 12\uFF1Bpadding 8px 2px 0\uFF1Bflex column\uFF1Boverflow hidden\uFF1Belevation-prominent \u9634\u5F71\uFF1B + border-l1 \u63CF\u8FB9\uFF08stroke \u7B49\u4EF7\uFF0C\u65E0 border\uFF09 */ +.team-panel { + width: min(500px, 100% - 32px); + max-height: min(680px, 100vh - 32px); + border-radius: 12px; + box-shadow: var(--at-shadow-prominent); + outline: 0.5px solid var(--at-border-l1); + background: var(--at-bg-menu); + padding: 8px 2px 0; + display: flex; + flex-direction: column; + overflow: hidden; + position: relative; +} +.team-panel.compact { width: min(320px, 100% - 32px); } +/* \xA710.3 body\uFF1Aoverflow-y auto\uFF1Bscrollbar-gutter stable\uFF1Bpadding 0 9px 16px 14px */ +.panel-body { + overflow-y: auto; + scrollbar-gutter: stable; + padding: 0 9px 16px 14px; + flex: auto; + min-height: 0; + scrollbar-color: var(--at-scrollbar-thumb) transparent; +} +.panel-body::-webkit-scrollbar { width: 8px; } +.panel-body::-webkit-scrollbar-thumb { + background: var(--at-scrollbar-thumb); + border-radius: 4px; +} +.panel-body::-webkit-scrollbar-thumb:hover { background: var(--at-scrollbar-thumb-hover); } +/* \xA710.5 \u8282\u6807\u9898\uFF1A13px/500\uFF0Cmargin 16px 0 8px 4px\uFF08\u9996\u8282 top 8px\uFF09\uFF0Cgap 8\uFF1B + count 12px/16px tabular-nums caption \u8272 */ +.panel-body h3 { + font-size: 13px; + font-weight: 500; + color: var(--at-label-primary); + margin: 16px 0 8px 4px; + display: flex; + align-items: center; + gap: 8px; +} +.panel-body section:first-of-type h3 { margin-top: 8px; } +h3 .count { + font-size: 12px; + line-height: 16px; + font-weight: 400; + color: var(--at-label-caption); + font-variant-numeric: tabular-nums; +} +/* \xA710.5 \u82B1\u540D\u518C\u7F51\u683C\uFF1A\u53CC\u5217 minmax(0,1fr) gap 8\uFF1B\u7D27\u51D1\u5355\u5217 */ +.roster { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } +.compact .roster { grid-template-columns: minmax(0, 1fr); } +/* \xA710.5 \u6210\u5458\u5361\uFF1A\u5706\u89D2 8\uFF1Bpadding 10px 12px\uFF1Bgap 8\uFF1Bbg-layer-2\uFF1B\u63CF\u8FB9 border-l2\uFF08stroke \u7B49\u4EF7\uFF09\uFF1B + \u6587\u5B57\u5DE6\u5BF9\u9F50\uFF1Bflex \u9876\u5BF9\u9F50\uFF1Bhover\uFF08\u975E\u7981\u7528\uFF09border-l3 + elevation-panel\uFF1Bdisabled cursor default */ +.member { + border-radius: 8px; + padding: 10px 12px; + gap: 8px; + background: var(--at-bg-layer-2); + box-shadow: 0 0 0 0.5px var(--at-border-l2); + border: none; + text-align: left; + display: flex; + align-items: flex-start; + font: inherit; + color: inherit; + min-width: 0; + cursor: pointer; +} +.member:disabled { cursor: default; } +.member:not(:disabled):hover, +.member:not(:disabled):focus-visible { + box-shadow: 0 0 0 0.5px var(--at-border-l3), var(--at-shadow-panel); +} +/* \u5F53\u524D\u4F1A\u8BDD\u9AD8\u4EAE\uFF08\u4EC5 members>1\uFF09\uFF1Abusiness 40% \u6DF7\u8272\u63CF\u8FB9 + inset 1px \u5185\u73AF */ +.member.current { + box-shadow: 0 0 0 0.5px color-mix(in srgb, var(--at-business) 40%, transparent), + inset 0 0 0 1px color-mix(in srgb, var(--at-business) 40%, transparent); +} +/* \u540D\u5B57/\u6B21\u884C\u6587\u672C\u5217\uFF08\xA710.5 memberText\uFF1Acolumn\uFF0Cmin-width 0 \u4F9B ellipsis\uFF09 */ +.member .member-text { display: flex; flex-direction: column; min-width: 0; gap: 2px; } +.member .row1 { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 100%; } +/* \u72B6\u6001\u70B9\u5BB9\u5668\uFF1A1lh \u9AD8\u5782\u76F4\u5BF9\u9F50\uFF08\xA710.5 memberDot\uFF09 */ +.member-dot { flex: none; align-items: center; height: 1lh; display: inline-flex; } +.member .name { + font-weight: 500; + color: var(--at-label-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; +} +.member .sub { + font-size: 11px; + color: var(--at-label-tertiary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100%; +} +/* hover/focus \u624D\u663E\u793A\u300C \xB7 \u6A21\u578B: model\u300D\uFF08\xA710.5/V06\uFF09 */ +.member .model { display: none; } +.member:hover .model, +.member:focus-visible .model { display: inline; } +.member .diagnostic { + font-size: 11px; + color: var(--at-error-text); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100%; +} +/* \u5F53\u524D\u4F1A\u8BDD Tag\uFF0810px/15px\uFF0Cpadding 0 4px\uFF0Cinfo tone\uFF09 */ +.current-tag { + font-size: 10px; + line-height: 15px; + padding: 0 4px; + border-radius: 4px; + background: color-mix(in srgb, var(--at-business) 16%, transparent); + color: var(--at-business); + flex: none; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +/* 0.4.0 \u6CE8\u9500\u6210\u5458\u5361/\u9F7F\u8F6E\u4E0E\u8BBE\u7F6E\u5F39\u7A97\u6837\u5F0F\uFF08member-card\u3001member-gear\u3001settings \u7CFB\u5217\u3001 + source-badge\u3001modal-select\uFF09\uFF1A\u6210\u5458\u6A21\u578B\u552F\u4E00\u8DEF\u7EBF = \u6BCF\u8F6E\u8DDF\u968F Lead\uFF0C\u9762\u677F\u6062\u590D\u96F6\u53D8\u66F4\u901A\u9053\u3002 */ +/* \u72B6\u6001\u70B9\uFF1A\u76F4\u5F84\u4E00\u81F4 8px\uFF08V06\uFF09 */ +.dot { width: 8px; height: 8px; border-radius: 50%; flex: none; display: inline-block; } +.dot.ongoing { background: var(--at-state-ongoing); } +.dot.error { background: var(--at-state-error); } +.dot.idle { background: var(--at-state-idle); } +.dot.warning { background: var(--at-state-warning); } +.dot.done { background: var(--at-state-done); } +/* inactive \u4EBA\u5F62\u56FE\u6807\uFF1A14px tertiary\uFF08\xA710.5/V06\uFF09 */ +.icon-user { width: 14px; height: 14px; flex: none; color: var(--at-label-tertiary); display: inline-flex; } +/* \xA710.4 \u901A\u77E5\u6761\uFF1Aflex gap 6 padding 9 \u5B57\u53F7 12\uFF1Berror = \u9519\u8BEF\u8272\uFF1B\u6309\u5E8F\u6E32\u67D3 */ +.notice, .error-bar { + display: flex; + align-items: center; + gap: 6px; + padding: 9px; + font-size: 12px; +} +.error-bar { color: var(--at-error-text); } +.notice { color: var(--at-label-secondary); } +/* \xA710.6 \u4EFB\u52A1\u677F\uFF1A\u7A7A\u677F\u6BB5\u843D 12px tertiary margin 16px 0 0 4px\uFF1B\u5217\u8868 flex column gap 7 */ +.empty-notice { font-size: 12px; color: var(--at-label-tertiary); margin: 16px 0 0 4px; } +.tasks { display: flex; flex-direction: column; gap: 7px; } +/* \u4EFB\u52A1\u5361\uFF1Aborder 0.5px border-l2\uFF1B\u5706\u89D2 9\uFF1Bpadding 11px 13px\uFF1Bbg-layer-2 */ +article.task { + border: 0.5px solid var(--at-border-l2); + border-radius: 9px; + padding: 11px 13px; + background: var(--at-bg-layer-2); +} +.task .title-row { display: flex; align-items: center; gap: 8px; } +.task strong { font-size: 13px; font-weight: 500; line-height: 1.4; color: var(--at-label-primary); } +/* \u72B6\u6001\u5FBD\u6807\u53F3\u5BF9\u9F50 11px gap 6 */ +.task .task-state { + margin-left: auto; + font-size: 11px; + color: var(--at-label-tertiary); + display: inline-flex; + align-items: center; + gap: 6px; + flex: none; +} +/* \u63CF\u8FF0 12px/18px pre-wrap margin 5px 0\uFF1B\u4E24\u884C\u622A\u65AD */ +.task p { + font-size: 12px; + line-height: 18px; + color: var(--at-label-secondary); + white-space: pre-wrap; + margin: 5px 0; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} +.task p.expanded { -webkit-line-clamp: unset; display: block; } +/* \u5C55\u5F00\u5F00\u5173\uFF1Afloat right\uFF1B11px/20px\uFF1Bchevron 12px \u65CB\u8F6C 180\xB0 transition .12s */ +.expand-toggle { + float: right; + font-size: 11px; + line-height: 20px; + color: var(--at-label-tertiary); + background: none; + border: none; + cursor: pointer; + padding: 0; + margin-left: 10px; + font-family: inherit; + display: inline-flex; + align-items: center; + gap: 2px; +} +.expand-toggle:hover, .expand-toggle:focus-visible { color: var(--at-label-primary); } +.expand-toggle svg { transition: transform 0.12s; } +.expand-toggle.open svg { transform: rotate(180deg); } +.expand-toggle[hidden] { display: none; } +/* meta \u884C\uFF1A11px/20px\uFF1B\u5B50\u9879\u95F4\u8DDD 10px\uFF1Bwarning \u63D0\u9192\u8272\uFF08advisory \u975E\u9519\u8BEF\uFF09 */ +.task .meta { font-size: 11px; line-height: 20px; color: var(--at-label-tertiary); } +.task .meta > span { margin-right: 10px; } +.task .meta .warning { color: var(--at-warning-text); } +/* T5.7 \u6210\u5458\u4F1A\u8BDD\u67E5\u770B\u89C6\u56FE\uFF08V16\uFF1A\u65E0 DSH \u53C2\u7167\uFF0C\u5BBF\u4E3B\u98CE\u683C\uFF1B\u5224\u636E=\u4E0D\u7834\u7248+\u51E0\u4F55\u4E00\u81F4\uFF09 */ +.detail-view { display: flex; flex-direction: column; min-height: 0; flex: auto; } +.detail-head { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 9px 8px 6px; + border-bottom: 0.5px solid var(--at-border-l2); + flex: none; +} +.detail-back { + display: inline-flex; + align-items: center; + gap: 4px; + background: none; + border: none; + color: var(--at-label-tertiary); + font: inherit; + font-size: 12px; + cursor: pointer; + padding: 2px 6px; + border-radius: 6px; +} +.detail-back:hover, .detail-back:focus-visible { color: var(--at-label-primary); background: color-mix(in srgb, var(--at-label-tertiary) 10%, transparent); } +.detail-title { font-size: 13px; font-weight: 500; color: var(--at-label-primary); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.detail-actions { margin-left: auto; display: inline-flex; gap: 6px; flex: none; } +.detail-action { + background: none; + border: 0.5px solid var(--at-border-l2); + border-radius: 6px; + color: var(--at-label-secondary); + font: inherit; + font-size: 11px; + line-height: 18px; + padding: 1px 8px; + cursor: pointer; +} +.detail-action:hover, .detail-action:focus-visible { color: var(--at-label-primary); border-color: var(--at-border-l3); } +.detail-list { overflow-y: auto; scrollbar-gutter: stable; padding: 8px 9px 16px 14px; flex: auto; min-height: 0; scrollbar-color: var(--at-scrollbar-thumb) transparent; } +.detail-state { font-size: 12px; color: var(--at-label-tertiary); padding: 16px 4px; display: flex; align-items: center; gap: 6px; } +.detail-state.error { color: var(--at-error-text); } +.msg { margin: 0 0 10px; min-width: 0; } +.msg-head { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--at-label-tertiary); margin-bottom: 2px; } +.msg-role { font-weight: 500; color: var(--at-label-secondary); } +.msg-time { font-variant-numeric: tabular-nums; } +.msg-text { + font-size: 12px; + line-height: 18px; + color: var(--at-label-primary); + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; +} +.msg.user .msg-text { color: var(--at-label-secondary); } +.msg-badge { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: 10px; + line-height: 15px; + padding: 0 4px; + border-radius: 4px; + background: color-mix(in srgb, var(--at-business) 16%, transparent); + color: var(--at-business); +} +.msg-badge.hook { background: color-mix(in srgb, var(--at-label-tertiary) 14%, transparent); color: var(--at-label-tertiary); } +.tool-row { display: block; width: 100%; text-align: left; background: none; border: none; border-top: 0.5px solid var(--at-border-l2); padding: 4px 0; margin-top: 4px; font: inherit; cursor: pointer; color: var(--at-label-tertiary); } +.tool-row:hover, .tool-row:focus-visible { color: var(--at-label-primary); } +.tool-static { display: block; border-top: 0.5px solid var(--at-border-l2); padding: 4px 0; margin-top: 4px; color: var(--at-label-tertiary); } +.tool-row .tool-summary, .tool-static .tool-summary { display: inline-flex; align-items: center; gap: 6px; font-size: 11px; line-height: 20px; } +.tool-row .tool-name, .tool-static .tool-name { font-weight: 500; color: var(--at-label-secondary); } +.tool-row svg { transition: transform 0.12s; } +.tool-row.open svg { transform: rotate(180deg); } +.tool-detail { + display: none; + font-size: 11px; + line-height: 16px; + color: var(--at-label-tertiary); + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; + max-height: 200px; + overflow-y: auto; + margin: 2px 0 0 18px; +} +.tool-row.open + .tool-detail { display: block; } +/* toolGroup\uFF1A\u6309\u8F6E\u52A8\u4F5C\u7EC4\uFF08\u5934\u90E8\u4E00\u884C\u6C47\u603B\uFF1B\u5C55\u5F00\u9010\u6761\u5DE5\u5177\u884C\uFF0C\u7F29\u8FDB\u5BF9\u9F50 tool-detail\uFF09 */ +.tool-group-head { + display: flex; + align-items: center; + gap: 6px; + width: 100%; + text-align: left; + background: none; + border: none; + border-top: 0.5px solid var(--at-border-l2); + padding: 4px 0; + margin-top: 4px; + font: inherit; + color: var(--at-label-tertiary); + cursor: pointer; +} +.tool-group-head:hover, .tool-group-head:focus-visible { color: var(--at-label-primary); } +.tool-group-head .tool-group-label { font-size: 11px; line-height: 20px; color: var(--at-label-secondary); } +.tool-group-head:hover .tool-group-label, +.tool-group-head:focus-visible .tool-group-label { color: var(--at-label-primary); } +.tool-group-head svg { flex: none; transition: transform 0.12s; } +.tool-group.open .tool-group-head svg { transform: rotate(180deg); } +.tool-group-items { display: none; margin-left: 18px; } +.tool-group.open .tool-group-items { display: block; } +.tool-group-items > :first-child { border-top: none; } +.detail-pager { display: flex; align-items: center; gap: 8px; padding: 4px 0 8px; } +.detail-pager .detail-action[disabled] { opacity: 0.45; cursor: default; } +`; +var CARD_CSS = ` +html, body { margin: 0; padding: 0; } +.at-root { display: flex; justify-content: center; padding: 16px 0; } +.team-panel { margin: 0 auto; } +`; + +// src/ui-core/dict.ts +var DICT = { + zh: { + trigger: "\u667A\u80FD\u4F53\u56E2\u961F", + loading: "\u6B63\u5728\u52A0\u8F7D\u56E2\u961F\u2026", + unavailable: "Team \u6682\u4E0D\u53EF\u7528", + failure: "\u56E2\u961F\u6301\u4E45\u8BB0\u5F55\u65E0\u6548\uFF1A{message}", + empty: "\u6682\u65E0\u5171\u4EAB\u4EFB\u52A1\uFF0C\u53EF\u4EE5\u901A\u8FC7\u5BF9\u8BDD\u521B\u5EFA", + roster: "\u6210\u5458", + tasks: "\u5171\u4EAB\u4EFB\u52A1", + model: "\u6A21\u578B", + open: "\u6253\u5F00\u6210\u5458\u4F1A\u8BDD", + current: "\u5F53\u524D\u4F1A\u8BDD", + owner: "Owner", + unowned: "\u672A\u5206\u914D", + blockedBy: "\u4F9D\u8D56", + writeScopes: "\u5199\u5165\u8303\u56F4", + ready: "\u53EF\u5F00\u59CB", + blocked: "\u88AB\u4F9D\u8D56\u963B\u585E", + "task.expand": "\u5C55\u5F00", + "task.collapse": "\u6536\u8D77", + "memberStatus.running": "\u8FD0\u884C\u4E2D", + "memberStatus.inactive": "\u672A\u8FD0\u884C", + "memberStatus.provisioning": "\u51C6\u5907\u4E2D", + "memberStatus.failed": "\u5931\u8D25", + "status.pending": "\u5F85\u5904\u7406", + "status.in_progress": "\u8FDB\u884C\u4E2D", + "status.completed": "\u5DF2\u5B8C\u6210" + }, + en: { + trigger: "Agent Team", + loading: "Loading Team\u2026", + unavailable: "Team is unavailable", + failure: "Invalid persisted Team record: {message}", + empty: "No shared tasks yet. Create them through the conversation.", + roster: "Members", + tasks: "Shared tasks", + model: "Model", + open: "Open member conversation", + current: "Current chat", + owner: "Owner", + unowned: "Unowned", + blockedBy: "Blocked by", + writeScopes: "Write scopes", + ready: "Ready", + blocked: "Blocked by dependencies", + "task.expand": "Show more", + "task.collapse": "Show less", + "memberStatus.running": "Running", + "memberStatus.inactive": "Inactive", + "memberStatus.provisioning": "Provisioning", + "memberStatus.failed": "Failed", + "status.pending": "Pending", + "status.in_progress": "In progress", + "status.completed": "Completed" + } +}; +function t(lang, key, vars) { + return interpolate(DICT[lang][key], vars); +} +function interpolate(template, vars) { + if (vars === void 0) return template; + return template.replace( + /\{(\w+)\}/g, + (m, k) => k in vars ? String(vars[k]) : m + ); +} +function statusKey(status) { + return status === "deleted" ? "status.completed" : `status.${status}`; +} +function memberStatusKey(status) { + return `memberStatus.${status}`; +} + +// src/ui-core/icons.ts +var svg = (inner, size) => ``; +function iconUser(size = 14) { + return svg('', size); +} +function iconChevron(size = 12) { + return svg('', size); +} + +// src/ui-core/escape.ts +function esc(s) { + return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); +} + +// src/ui-core/render.ts +function isCompact(frame) { + return frame.members.length === 1 && frame.tasks.length === 0; +} +function currentMemberId(frame) { + const sid = frame.meta.sessionId; + if (sid === void 0) return void 0; + return frame.members.find((m) => m.sessionId === sid)?.id; +} +function isMemberDisabled(m, currentId) { + return m.id === currentId || m.status === "failed" || m.status === "provisioning"; +} +function memberDot(status) { + switch (status) { + case "running": + case "provisioning": + return "ongoing"; + case "failed": + return "error"; + case "inactive": + default: + return "icon"; + } +} +function taskDot(task) { + switch (task.status) { + case "in_progress": + return "ongoing"; + case "completed": + return "done"; + case "deleted": + return "idle"; + // 上游 deleted→idle(视图通常不含墓碑,防御口径) + case "pending": + default: + return task.ready ? "idle" : "warning"; + } +} +function dot(state) { + return ``; +} +function memberIndicator(m) { + const d = memberDot(m.status); + const inner = d === "icon" ? `${iconUser(14)}` : dot(d); + return `${inner}`; +} +function renderMember(m, opts) { + const { lang, isCurrent, disabled } = opts; + const highlight = opts.highlightCurrent ?? isCurrent; + const cls = ["member", highlight ? "current" : ""].filter(Boolean).join(" "); + const nameRow = `${esc(m.target)}` + (isCurrent ? `${esc(t(lang, "current"))}` : "") + ``; + const modelSuffix = m.model !== void 0 ? ` \xB7 ${esc(t(lang, "model"))}: ${esc(m.model)}` : ""; + const sub = `${esc(t(lang, memberStatusKey(m.status)))}${modelSuffix}`; + const diag = m.diagnostics.length > 0 ? `${esc(m.diagnostics[0])}` : ""; + const openAttr = disabled ? "" : ` title="${esc(t(lang, "open"))}"`; + return ``; +} +function renderRoster(frame, lang) { + const members = frame.members; + const currentId = currentMemberId(frame); + const countHtml = members.length > 1 ? `${members.length}` : ""; + const cards = members.map( + (m) => renderMember(m, { + lang, + // Tag 恒随当前会话;高亮/描边才受 members>1 限制(上游 TeamAction 同口径)。 + isCurrent: m.id === currentId, + highlightCurrent: m.id === currentId && members.length > 1, + disabled: isMemberDisabled(m, currentId) + }) + ).join(""); + return `

${esc(t(lang, "roster"))}${countHtml}

${cards}
`; +} +function renderTaskMeta(task, lang, leadingHtml = "") { + const spans = []; + spans.push(`${esc(task.id)}`); + const owner = task.ownerName !== void 0 ? esc(task.ownerName) : esc(t(lang, "unowned")); + spans.push(`${esc(t(lang, "owner"))}: ${owner}`); + if (task.status === "pending") { + spans.push(`${esc(t(lang, task.ready ? "ready" : "blocked"))}`); + } + if (task.blockedBy.length > 0) { + spans.push(`${esc(t(lang, "blockedBy"))}: ${task.blockedBy.map(esc).join(", ")}`); + } + if (task.writeScopes.length > 0) { + spans.push(`${esc(t(lang, "writeScopes"))}: ${task.writeScopes.map(esc).join(", ")}`); + } + for (const w of task.writeScopeWarnings) { + spans.push(`${esc(w)}`); + } + return `
${leadingHtml}${spans.join("")}
`; +} +function renderTask(task, lang) { + const state = `${dot(taskDot(task))}${esc(t(lang, statusKey(task.status)))}`; + const titleRow = `
${esc(task.subject)}${state}
`; + const toggle = ``; + const desc = `

${esc(task.description)}

`; + return `
` + titleRow + desc + renderTaskMeta(task, lang, toggle) + `
`; +} +function renderTasks(frame, lang) { + if (frame.tasks.length === 0) { + return `

${esc(t(lang, "empty"))}

`; + } + const cards = frame.tasks.map((task) => renderTask(task, lang)).join(""); + return `

${esc(t(lang, "tasks"))}${frame.tasks.length}

${cards}
`; +} +function renderNotices(opts) { + const { lang } = opts; + const out = []; + if (opts.navError !== void 0) { + out.push(``); + } + if (opts.loading === true) { + out.push(`
${dot("ongoing")}${esc(t(lang, "loading"))}
`); + } else if (opts.noTeam === true) { + out.push(`
${dot("warning")}${esc(t(lang, "unavailable"))}
`); + } + if (opts.failure !== void 0) { + out.push(``); + } + return out.join(""); +} +function renderPanelBody(frame, lang, runtime) { + const noTeam = frame.team === null; + const notices = renderNotices({ + lang, + ...runtime?.navError !== void 0 ? { navError: runtime.navError } : {}, + ...runtime?.loading !== void 0 ? { loading: runtime.loading } : {}, + noTeam, + ...frame.team?.failure !== void 0 ? { failure: frame.team.failure } : {} + }); + if (noTeam && runtime?.loading !== true) { + return notices; + } + return notices + renderRoster(frame, lang) + renderTasks(frame, lang); +} + +// src/ui-core/widget.ts +function renderWidgetFragment(opts) { + const lang = opts.lang ?? "zh"; + const theme = opts.theme ?? "light"; + const rootId = opts.rootId ?? "agent-team-widget"; + const compact = isCompact(opts.frame); + const body = renderPanelBody(opts.frame, lang, { loading: false }); + const frameJson = esc(JSON.stringify(opts.frame)); + return `
`; +} +function renderStandalonePage(opts) { + const lang = opts.lang ?? "zh"; + const theme = opts.theme ?? "light"; + return ` + + + + +${esc(opts.title ?? t(lang, "trigger"))} + + + +${renderWidgetFragment(opts)} + + +`; +} +var WIDGET_SCRIPT = ` +var root = document.getElementById(__AT_ROOT_ID__); +if (!root) return; +var labels = { expand: '\u5C55\u5F00', collapse: '\u6536\u8D77' }; +try { labels = JSON.parse(root.getAttribute('data-labels') || '{}') || labels; } catch (e) {} +var store = { set: {} }; +try { + var ws = window.zcode && window.zcode.widgetState; + if (ws && Array.isArray(ws.expanded)) { for (var i=0;i desc.clientHeight + 1; + toggle.hidden = !(overflow || expanded); + var lbl = toggle.querySelector('.expand-label'); + if (lbl) lbl.textContent = expanded ? (labels.collapse||'\u6536\u8D77') : (labels.expand||'\u5C55\u5F00'); + toggle.setAttribute('aria-expanded', expanded ? 'true' : 'false'); + toggle.classList.toggle('open', expanded); + desc.classList.toggle('expanded', expanded); +} +var tasks = root.querySelectorAll('article.task'); +for (var j=0;j resolveMemberSession(input.teamDir, dataRootOf(input.teamDir), memberId) + ); + const member = input.loaded.state.members.find((m) => m.id === result.memberId || m.name === input.member); + if (member !== void 0) name = member.name; + if (input.member === "lead" || input.member === input.teamId) name = "lead"; + } finally { + reader.close(); + } + if (input.json) return JSON.stringify({ ...result, memberName: name }, null, 2); + return renderDetailText(result, name); +} +function renderWidget(input) { + const frame = buildStaticFrame( + input.loaded, + input.teamId, + (/* @__PURE__ */ new Date()).toISOString(), + input.sessionId, + input.teamDir, + dataRootOf(input.teamDir) + ); + const html = input.standalone ? renderStandalonePage({ frame, lang: input.lang, theme: input.theme }) : renderWidgetFragment({ frame, lang: input.lang, theme: input.theme }); + if (input.out !== void 0) { + const abs = safeOutPath(input.out); + fs9.mkdirSync(path10.dirname(abs), { recursive: true }); + fs9.writeFileSync(abs, html); + return { html, out: abs }; + } + return { html }; +} +function safeOutPath(out) { + if (out.split(/[\\/]/).includes("..")) { + throw new Error(`--out \u62D2\u7EDD\u8DEF\u5F84\u7A7F\u8D8A\u6BB5 ".."\uFF1A${out}`); + } + const abs = path10.resolve(out); + const base = path10.basename(abs); + if (!/^[A-Za-z0-9._-]+\.html$/.test(base)) { + throw new Error(`--out \u6587\u4EF6\u540D\u987B\u4E3A\u767D\u540D\u5355\u5B57\u7B26\u4E14 .html \u540E\u7F00\uFF08[A-Za-z0-9._-]\uFF09\uFF1A${base}`); + } + return abs; +} + +// src/cli/open-panel.ts +import fs10 from "node:fs"; +import net2 from "node:net"; +import { execFile } from "node:child_process"; + +// src/panel/companion-server.ts +import path11 from "node:path"; +var COMPANION_REGISTRY_RELPATH = "logs/panel-http.json"; +function companionRegistryFile(dataRoot) { + const root = path11.resolve(dataRoot); + const file = path11.join(root, COMPANION_REGISTRY_RELPATH); + if (file !== path11.join(root, "logs", "panel-http.json")) { + throw new Error("companion registry path escapes dataRoot"); + } + return file; +} + +// src/cli/open-panel.ts +var NOT_RUNNING = "\u4F34\u751F\u9762\u677F\u672A\u8FD0\u884C\uFF08\u65E0 logs/panel-http.json\uFF09\u3002\u4EE5 TEAM_COMPANION=1 \u542F\u52A8 team-daemon \u540E\u91CD\u8BD5\uFF08MCP Apps \u9762\u677F/::visualize \u5361\u7247\u4E3A\u4E3B\u8F7D\u4F53\uFF0C\u4F34\u751F\u9762\u677F\u4E3A\u53EF\u9009\u9AD8\u4FDD\u771F\u8DEF\u5F84\uFF09\u3002"; +async function openPanel(input = {}) { + const registryFile = companionRegistryFile(input.dataRoot ?? dataDir()); + let reg; + try { + reg = JSON.parse(fs10.readFileSync(registryFile, "utf8")); + } catch { + return { ok: false, message: NOT_RUNNING }; + } + if (typeof reg.port !== "number" || !Number.isInteger(reg.port) || reg.port < 1 || reg.port > 65535 || typeof reg.token !== "string" || !/^[0-9a-f]{32}$/.test(reg.token)) { + return { ok: false, message: "logs/panel-http.json \u5185\u5BB9\u975E\u6CD5\uFF08port/token \u6821\u9A8C\u5931\u8D25\uFF09\u3002" }; + } + const url = `http://127.0.0.1:${reg.port}/panel?token=${reg.token}`; + const alive = await probePort(reg.port); + if (!alive) { + return { + ok: false, + port: reg.port, + message: `\u4F34\u751F\u9762\u677F\u7AEF\u53E3 ${reg.port} \u672A\u76D1\u542C\uFF08daemon \u53EF\u80FD\u5DF2\u56DE\u6536\uFF09\u3002\u4EE5 TEAM_COMPANION=1 \u91CD\u542F daemon \u540E\u91CD\u8BD5\u3002` + }; + } + if (input.noOpen !== true) void launchBrowser(url); + return { ok: true, url, port: reg.port, message: url }; +} +function probePort(port) { + return new Promise((resolve) => { + const socket = net2.connect({ host: "127.0.0.1", port }, () => { + socket.destroy(); + resolve(true); + }); + socket.setTimeout(1500); + socket.once("timeout", () => { + socket.destroy(); + resolve(true); + }); + socket.once("error", () => { + socket.destroy(); + resolve(false); + }); + }); +} +function launchBrowser(url) { + const platform = process.platform; + const [cmd, args] = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]]; + return new Promise((resolve) => { + execFile(cmd, [...args], { windowsHide: true }, () => resolve()); + }); +} + +// src/cli/sidebar-audit.ts +import fs12 from "node:fs"; +import path13 from "node:path"; + +// src/sidebar/tasks-index.ts +import fs11 from "node:fs"; +import os4 from "node:os"; +import path12 from "node:path"; +import { DatabaseSync as DatabaseSync2 } from "node:sqlite"; +var ANCHOR_TITLE = "Agent Team anchor"; +function defaultTasksIndexPath() { + return process.env.TEAM_TASKS_INDEX ?? path12.join(os4.homedir(), ".zcode", "v2", "tasks-index.sqlite"); +} +function withRetry(fn, attempts = 3) { + let last; + for (let i = 0; i < attempts; i += 1) { + try { + return fn(); + } catch (err) { + last = err; + const message = err instanceof Error ? err.message : String(err); + if (!/SQLITE_BUSY|database is locked/i.test(message)) throw err; + const until = Date.now() + 100 * (i + 1); + while (Date.now() < until) { + } + } + } + throw last; +} +function readTask(dbPath, taskId) { + if (!fs11.existsSync(dbPath)) return void 0; + const db = new DatabaseSync2(dbPath, { readOnly: true }); + try { + return db.prepare("select task_id, title, archived, deleted, workspace_path from tasks where task_id = ?").get(taskId); + } finally { + db.close(); + } +} +function tombstoneAnchor(input) { + const dbPath = input.dbPath ?? defaultTasksIndexPath(); + if (!fs11.existsSync(dbPath)) return { applied: false, reason: "tasks-index-missing" }; + const now = input.now ?? Date.now(); + return withRetry(() => { + const db = new DatabaseSync2(dbPath); + try { + db.exec("PRAGMA busy_timeout = 5000"); + db.exec("BEGIN IMMEDIATE"); + const existing = db.prepare("select task_id, title, workspace_path from tasks where task_id = ?").get(input.taskId); + if (existing !== void 0 && existing.workspace_path === input.workspacePath && existing.title !== "" && existing.title !== "Untitled session" && existing.title !== ANCHOR_TITLE) { + db.exec("ROLLBACK"); + return { applied: false, reason: "row-not-owned" }; + } + if (existing !== void 0 && existing.workspace_path !== input.workspacePath) { + db.exec("ROLLBACK"); + return { applied: false, reason: "row-not-owned" }; + } + const meta = JSON.stringify({ + taskId: input.taskId, + title: ANCHOR_TITLE, + workspacePath: input.workspacePath, + createdAt: now, + updatedAt: now, + mode: "default", + provider: "glm", + status: "completed", + titleOverridden: false + }); + db.prepare( + `INSERT INTO tasks ( + workspace_key, workspace_path, workspace_identity, task_id, title, task_status, + provider, mode, model, migration_source, forked_from_task_id, cron_automation_id, + off_peak_task_id, created_at, updated_at, unread_at, last_unread_at, pinned, + archived, deleted, title_overridden, searchable_text, meta_json + ) VALUES ( + @workspace_key, @workspace_path, NULL, @task_id, @title, 'completed', + 'glm', 'default', NULL, NULL, NULL, NULL, + NULL, @now, @now, NULL, 0, 0, + 0, 1, 0, @searchable, @meta + ) + ON CONFLICT(workspace_key, task_id) DO UPDATE SET + deleted = 1, + updated_at = excluded.updated_at + WHERE tasks.task_id = excluded.task_id + AND (tasks.title = '' OR tasks.title = 'Untitled session' OR tasks.title = @title)` + ).run({ + workspace_key: input.workspacePath, + workspace_path: input.workspacePath, + task_id: input.taskId, + title: ANCHOR_TITLE, + now, + searchable: ANCHOR_TITLE, + meta + }); + db.exec("COMMIT"); + return { applied: true }; + } catch (err) { + try { + db.exec("ROLLBACK"); + } catch { + } + throw err; + } finally { + db.close(); + } + }); +} +function archiveTask(input) { + const dbPath = input.dbPath ?? defaultTasksIndexPath(); + if (!fs11.existsSync(dbPath)) return { applied: false, reason: "tasks-index-missing" }; + const now = input.now ?? Date.now(); + return withRetry(() => { + const db = new DatabaseSync2(dbPath); + try { + db.exec("PRAGMA busy_timeout = 5000"); + db.exec("BEGIN IMMEDIATE"); + const existing = db.prepare("select task_id, workspace_path, archived from tasks where task_id = ?").get(input.taskId); + if (existing === void 0 || existing.workspace_path !== input.workspacePath) { + db.exec("ROLLBACK"); + return { applied: false, reason: "row-not-owned" }; + } + if (existing.archived === 1) { + db.exec("COMMIT"); + return { applied: false }; + } + db.prepare("update tasks set archived = 1, updated_at = ? where task_id = ?").run(now, input.taskId); + db.exec("COMMIT"); + return { applied: true }; + } catch (err) { + try { + db.exec("ROLLBACK"); + } catch { + } + throw err; + } finally { + db.close(); + } + }); +} + +// src/cli/sidebar-audit.ts +function listMemberIds(teamDir) { + try { + return fs12.readdirSync(path13.join(teamDir, "members")).filter((n) => !n.startsWith(".")).sort(); + } catch { + return []; + } +} +function auditSidebar(input) { + const teamDir = path13.resolve(input.teamDir); + const tasksIndexPath = input.tasksIndexPath ?? defaultTasksIndexPath(); + const dryRun = input.dryRun ?? true; + const entries = []; + const seenAnchors = /* @__PURE__ */ new Set(); + for (const memberId of listMemberIds(teamDir)) { + const origin = readOrigin(memberPaths(teamDir, memberId)); + if (origin === void 0 || origin.sessionId === null) continue; + const sessionId = origin.sessionId; + const isolation = origin.sessionIsolation ?? "unknown"; + const row = readTask(tasksIndexPath, sessionId); + const expectedWorkspace = path13.resolve(origin.cwd); + const owned = row !== void 0 && path13.resolve(row.workspace_path) === expectedWorkspace; + const needsArchive = owned && row.archived !== 1; + let action; + if (row === void 0) { + action = "absent"; + } else if (!owned) { + action = "mismatch"; + } else if (!needsArchive) { + action = "already-archived"; + } else { + action = dryRun ? "would-archive" : "archived"; + } + entries.push({ + memberId, + name: origin.name ?? null, + sessionId, + sessionIsolation: isolation, + action, + kind: "member", + ...row !== void 0 ? { title: row.title } : {} + }); + if (!dryRun && needsArchive) { + const result = archiveTask({ taskId: sessionId, workspacePath: row.workspace_path, dbPath: tasksIndexPath }); + entries[entries.length - 1].action = result.applied ? "archived" : result.reason === "row-not-owned" ? "mismatch" : "absent"; + } + const anchorId = origin.anchorSessionId; + if (typeof anchorId === "string" && anchorId.length > 0 && !seenAnchors.has(anchorId)) { + seenAnchors.add(anchorId); + const anchorRow = readTask(tasksIndexPath, anchorId); + const anchorOwned = anchorRow !== void 0 && path13.resolve(anchorRow.workspace_path) === expectedWorkspace; + let anchorAction; + if (anchorRow === void 0) { + anchorAction = "absent"; + } else if (!anchorOwned) { + anchorAction = "mismatch"; + } else if (anchorRow.deleted === 1) { + anchorAction = "already-tombstoned"; + } else { + anchorAction = dryRun ? "would-tombstone" : "tombstoned"; + } + entries.push({ + memberId, + name: origin.name ?? null, + sessionId: anchorId, + sessionIsolation: isolation, + action: anchorAction, + kind: "anchor", + ...anchorRow !== void 0 ? { title: anchorRow.title } : {} + }); + if (!dryRun && anchorOwned && anchorRow.deleted !== 1) { + const result = tombstoneAnchor({ + taskId: anchorId, + workspacePath: anchorRow.workspace_path, + dbPath: tasksIndexPath + }); + entries[entries.length - 1].action = result.applied ? "tombstoned" : result.reason === "row-not-owned" ? "mismatch" : "absent"; + } + } + } + const applied = entries.filter((e) => e.action === "archived" || e.action === "tombstoned").length; + const tombstoned = entries.filter((e) => e.action === "tombstoned").length; + let ledgerPath = null; + if (!dryRun) { + ledgerPath = path13.join(teamDir, "sidebar-migration.json"); + const now = input.now ?? Date.now; + const ledger = { + kind: "sidebar-audit", + version: 1, + at: new Date(now()).toISOString(), + tasksIndexPath, + entries + }; + writeAtomic(ledgerPath, ledger); + } + return { teamDir, tasksIndexPath, dryRun, entries, applied, tombstoned, ledgerPath }; +} +function writeAtomic(file, value) { + const tmp = `${file}.tmp-${process.pid}`; + fs12.writeFileSync(tmp, `${JSON.stringify(value, null, 2)} +`, { mode: 384 }); + fs12.renameSync(tmp, file); +} +function renderSidebarAudit(result) { + const lines = []; + lines.push(`sidebar-audit ${result.teamDir}`); + lines.push(`tasks-index: ${result.tasksIndexPath}`); + lines.push(`mode: ${result.dryRun ? "dry-run\uFF08\u52A0 --apply \u624D\u5199\u5E93\uFF09" : "apply"}`); + if (result.entries.length === 0) { + lines.push("\uFF08\u6CA1\u6709\u5DF2\u843D\u5B9A\u7684\u6210\u5458\u4F1A\u8BDD\uFF09"); + return lines.join("\n"); + } + for (const e of result.entries) { + const label = e.name !== null ? `${e.name} (${e.memberId})` : e.memberId; + const kind = e.kind === "anchor" ? "anchor" : "member"; + const title = e.title !== void 0 ? ` \xB7 ${e.title}` : ""; + lines.push(`- ${label} [${kind}/${e.sessionIsolation}] ${e.sessionId} \u2192 ${e.action}${title}`); + } + lines.push( + result.dryRun ? `\u8BA1\u5212\u5F52\u6863 ${result.entries.filter((e) => e.action === "would-archive").length} \u6761\u3001tombstone ${result.entries.filter((e) => e.action === "would-tombstone").length} \u4E2A anchor\uFF1B\u672A\u5199\u5E93\u3002` : `\u5DF2\u5F52\u6863 ${result.applied - result.tombstoned} \u6761\u3001tombstone ${result.tombstoned} \u4E2A anchor\uFF1B\u53F0\u8D26 ${result.ledgerPath}` + ); + return lines.join("\n"); +} + +// src/cli/main.ts +var USAGE = `team-ctl \u2014 Agent Teams \u8FD0\u7EF4/\u6392\u969C\u5DE5\u5177 + +\u7528\u6CD5\uFF1A + team-ctl state [--json] [--team ] \u8BFB\u76D8\u91CD\u653E\uFF1ARoster/Tasks/Mailbox \u5206\u533A\u89C6\u56FE + team-ctl tail [--n ] \u8DDF\u968F events.jsonl\uFF08\u56DB\u7C7B\u4E8B\u4EF6\u7740\u8272\uFF0C\u672C\u5730\u65F6\u533A\uFF09 + team-ctl inject-event \u76F4\u5199\u539F\u59CB\u4E8B\u4EF6\u884C\uFF08test-only\uFF0C\u7ED5\u8FC7 journal\uFF09 + team-ctl inject-event --sample invalid-member --team + \u6CE8\u5165\u975E\u6CD5 member \u4E8B\u4EF6\u6837\u4F8B\uFF08\u91CD\u653E \u2192 failure \u7EC8\u6001\uFF09 + team-ctl call [params-json] \u7ECF socket \u8C03\u534F\u8C03\u8005\uFF08\u65E0\u534F\u8C03\u8005 \u2192 \u53EF\u8BFB\u9519\u8BEF\uFF09 + team-ctl transcript [--json] [--cursor ] [--limit ] [--team ] + \u6210\u5458\u4F1A\u8BDD\u67E5\u770B\u6D41\uFF08T5.7 CLI \u5BF9\u7B49\uFF1B\u4E0E\u9762\u677F detail \u540C\u4E00\u5408\u6210\uFF09 + team-ctl widget [--out ] [--theme light|dark] [--lang zh|en] [--standalone] + ::visualize \u5FEB\u7167\u5361\u7247\u7247\u6BB5 / standalone \u9759\u6001\u9875\uFF08T5.3 CLI \u964D\u7EA7\u94FE\uFF09 + team-ctl open-panel [--no-open] \u6253\u5F00\u4F34\u751F\u9762\u677F\uFF08T5.5\uFF1Bdaemon \u9700\u4EE5 TEAM_COMPANION=1 \u8FD0\u884C\uFF09 + team-ctl sidebar-audit [--apply] [--json] \u628A\u5DF2\u6CC4\u6F0F\u5230\u5DE6\u4FA7\u4EFB\u52A1\u680F\u7684\u6210\u5458\u4F1A\u8BDD\u5F52\u6863\uFF08\u9ED8\u8BA4 dry-run\uFF09`; +async function main(argv) { + const [command, ...rest] = argv; + if (command === void 0 || command === "help" || command === "--help") { + process.stdout.write(USAGE + "\n"); + return command === void 0 ? 2 : 0; + } + try { + switch (command) { + case "state": + return await cmdState(rest); + case "tail": + return await cmdTail(rest); + case "inject-event": + return cmdInject(rest); + case "call": + return await cmdCall(rest); + case "transcript": + return await cmdTranscript(rest); + case "widget": + return await cmdWidget(rest); + case "open-panel": + return await cmdOpenPanel(rest); + case "sidebar-audit": + return cmdSidebarAudit(rest); + default: + process.stderr.write(`team-ctl: \u672A\u77E5\u5B50\u547D\u4EE4 ${JSON.stringify(command)} + +${USAGE} +`); + return 2; + } + } catch (err) { + const first = err instanceof Error ? err.message.split("\n")[0] : String(err); + process.stderr.write(`team-ctl ${command}: ${first} +`); + return 1; + } +} +var invokedPath = process.argv[1]; +if (invokedPath !== void 0 && import.meta.url === pathToFileURL(path14.resolve(invokedPath)).href) { + process.exitCode = await main(process.argv.slice(2)); +} +function takeFlag(rest, name) { + const i = rest.indexOf(name); + return i >= 0 ? rest[i + 1] : void 0; +} +function resolveTeamId(teamDir, explicit) { + if (explicit !== void 0) return explicit; + const eventsFile = path14.join(teamDir, "events.jsonl"); + if (fs13.existsSync(eventsFile)) { + const first = fs13.readFileSync(eventsFile, "utf8").split("\n", 1)[0]; + if (first !== void 0 && first.length > 0) { + try { + const parsed = JSON.parse(first); + if (typeof parsed.event?.teamId === "string") return parsed.event.teamId; + } catch { + } + } + } + const base = path14.basename(teamDir); + if (base.length === 0) throw new Error("\u65E0\u6CD5\u63A8\u65AD teamId\uFF1A\u7A7A\u76EE\u5F55\u540D\uFF1B\u8BF7\u4F20 --team "); + return base; +} +async function cmdState(rest) { + const teamDir = rest[0]; + if (teamDir === void 0 || teamDir.startsWith("--")) { + process.stderr.write("team-ctl state: \u9700\u8981 \n"); + return 2; + } + const json = rest.includes("--json"); + const teamId = resolveTeamId(teamDir, takeFlag(rest, "--team")); + const loaded = await load(teamDir, teamId); + process.stdout.write(renderState({ teamId, loaded, json }, paintForStream(process.stdout)) + "\n"); + return 0; +} +async function cmdTail(rest) { + const teamDir = rest[0]; + if (teamDir === void 0 || teamDir.startsWith("--")) { + process.stderr.write("team-ctl tail: \u9700\u8981 \n"); + return 2; + } + const nFlag = takeFlag(rest, "--n"); + const fromLines = nFlag !== void 0 ? Number(nFlag) : void 0; + if (fromLines !== void 0 && (!Number.isInteger(fromLines) || fromLines < 0)) { + process.stderr.write("team-ctl tail: --n \u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570\n"); + return 2; + } + const controller = new AbortController(); + process.once("SIGINT", () => controller.abort()); + process.once("SIGTERM", () => controller.abort()); + await followEvents(eventsFileOf(teamDir), { + fromLines, + paint: paintForStream(process.stdout), + signal: controller.signal, + onLine: (formatted) => process.stdout.write(formatted + "\n") + }); + return 0; +} +function cmdInject(rest) { + const teamDir = rest[0]; + if (teamDir === void 0 || teamDir.startsWith("--")) { + process.stderr.write("team-ctl inject-event: \u9700\u8981 \n"); + return 2; + } + const sample = takeFlag(rest, "--sample"); + let line = rest[1]; + if (sample === "invalid-member") { + const teamId = resolveTeamId(teamDir, takeFlag(rest, "--team")); + line = invalidMemberSample(teamId); + } else if (sample !== void 0) { + process.stderr.write(`team-ctl inject-event: \u672A\u77E5\u6837\u4F8B ${JSON.stringify(sample)}\uFF08\u53EF\u7528\uFF1Ainvalid-member\uFF09 +`); + return 2; + } + if (line === void 0 || line.startsWith("--")) { + process.stderr.write("team-ctl inject-event: \u9700\u8981 \uFF08\u6216 --sample invalid-member\uFF09\n"); + return 2; + } + const result = injectEvent(teamDir, line); + process.stdout.write( + [ + `test-only\uFF1A\u5DF2\u7ED5\u8FC7 journal \u76F4\u5199\uFF08\u65E0\u4E0D\u53D8\u91CF/\u65E0\u9501/\u65E0 fsync\uFF09`, + `seq=${result.seq} file=${result.file}`, + result.line, + JSON.stringify({ tool: "team-ctl", action: "inject-event", teamDir, seq: result.seq, ok: true }), + "" + ].join("\n") + ); + return 0; +} +async function cmdCall(rest) { + const [teamDir, method, paramsJson] = rest; + if (teamDir === void 0 || method === void 0 || teamDir.startsWith("--")) { + process.stderr.write("team-ctl call: \u9700\u8981 [params-json]\n"); + return 2; + } + const outcome = await callTeam(teamDir, method, paramsJson); + process.stdout.write(outcome.output + "\n"); + process.stderr.write(outcome.audit + "\n"); + return outcome.ok ? 0 : 1; +} +async function cmdTranscript(rest) { + const teamDir = rest[0]; + const member = rest[1]; + if (teamDir === void 0 || member === void 0 || teamDir.startsWith("--") || member.startsWith("--")) { + process.stderr.write("team-ctl transcript: \u9700\u8981 \n"); + return 2; + } + const teamId = resolveTeamId(teamDir, takeFlag(rest, "--team")); + const loaded = await load(teamDir, teamId); + const cursorFlag = takeFlag(rest, "--cursor"); + const limitFlag = takeFlag(rest, "--limit"); + const cursor = cursorFlag !== void 0 ? Number(cursorFlag) : void 0; + const limit = limitFlag !== void 0 ? Number(limitFlag) : void 0; + if (cursor !== void 0 && !Number.isSafeInteger(cursor)) { + process.stderr.write("team-ctl transcript: --cursor \u5FC5\u987B\u662F\u5B89\u5168\u6574\u6570\n"); + return 2; + } + if (limit !== void 0 && !Number.isSafeInteger(limit)) { + process.stderr.write("team-ctl transcript: --limit \u5FC5\u987B\u662F\u5B89\u5168\u6574\u6570\n"); + return 2; + } + const out = renderTranscript({ + teamDir, + teamId, + loaded, + member, + json: rest.includes("--json"), + ...cursor !== void 0 ? { cursor } : {}, + ...limit !== void 0 ? { limit } : {} + }); + process.stdout.write(out + "\n"); + return 0; +} +async function cmdWidget(rest) { + const teamDir = rest[0]; + if (teamDir === void 0 || teamDir.startsWith("--")) { + process.stderr.write("team-ctl widget: \u9700\u8981 \n"); + return 2; + } + const teamId = resolveTeamId(teamDir, takeFlag(rest, "--team")); + const loaded = await load(teamDir, teamId); + const theme = takeFlag(rest, "--theme"); + if (theme !== void 0 && theme !== "light" && theme !== "dark") { + process.stderr.write("team-ctl widget: --theme \u4EC5\u652F\u6301 light|dark\n"); + return 2; + } + const langFlag = takeFlag(rest, "--lang"); + if (langFlag !== void 0 && langFlag !== "zh" && langFlag !== "en") { + process.stderr.write("team-ctl widget: --lang \u4EC5\u652F\u6301 zh|en\n"); + return 2; + } + const result = renderWidget({ + teamDir, + teamId, + loaded, + theme: theme ?? "light", + lang: langFlag ?? "zh", + standalone: rest.includes("--standalone"), + ...takeFlag(rest, "--out") !== void 0 ? { out: takeFlag(rest, "--out") } : {} + }); + if (result.out !== void 0) { + process.stdout.write(`${result.out} +`); + } else { + process.stdout.write(result.html + "\n"); + } + return 0; +} +function cmdSidebarAudit(rest) { + const teamDir = rest[0]; + if (teamDir === void 0 || teamDir.startsWith("--")) { + process.stderr.write("team-ctl sidebar-audit: \u9700\u8981 \n"); + return 2; + } + const result = auditSidebar({ + teamDir, + dryRun: !rest.includes("--apply"), + ...takeFlag(rest, "--tasks-index") !== void 0 ? { tasksIndexPath: takeFlag(rest, "--tasks-index") } : {} + }); + process.stdout.write( + rest.includes("--json") ? `${JSON.stringify(result, null, 2)} +` : `${renderSidebarAudit(result)} +` + ); + return 0; +} +async function cmdOpenPanel(rest) { + const result = await openPanel({ noOpen: rest.includes("--no-open") }); + process.stdout.write(result.message + "\n"); + return result.ok ? 0 : 1; +} +export { + main +}; diff --git a/external_plugins/agent-team/runtime/team-daemon.mjs b/external_plugins/agent-team/runtime/team-daemon.mjs new file mode 100644 index 00000000..f6211f6f --- /dev/null +++ b/external_plugins/agent-team/runtime/team-daemon.mjs @@ -0,0 +1,28234 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); + +// node_modules/ajv/dist/compile/codegen/code.js +var require_code = __commonJS({ + "node_modules/ajv/dist/compile/codegen/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class { + }; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) + throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) + return false; + const item = this._items[0]; + return item === "" || item === '""'; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) + names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + var plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) + code.push(...arg._items); + else if (arg instanceof Name) + code.push(arg); + else + code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === '""') + return a; + if (a === '""') + return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== '"') + return; + if (typeof b != "string") + return `${a.slice(0, -1)}${b}"`; + if (b[0] === '"') + return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) + return `"${a}${b.slice(1)}`; + return; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify2(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify2; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) { + return new _Code(`${key}`); + } + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; + } +}); + +// node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = __commonJS({ + "node_modules/ajv/dist/compile/codegen/scope.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + var code_1 = require_code(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState2) { + UsedValueState2[UsedValueState2["Started"] = 0] = "Started"; + UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) { + throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + } + return this._names[prefix] = { prefix, index: 0 }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + var line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { ...opts, _n: opts.lines ? line : code_1.nil }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) + throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) + return _name; + } else { + vs = this._values[prefix] = /* @__PURE__ */ new Map(); + } + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { property: prefix, itemIndex }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) + return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) + throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) + continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) + return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) { + code = (0, code_1._)`${code}${c}${this.opts._n}`; + } else { + throw new ValueError(name); + } + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; + } +}); + +// node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = __commonJS({ + "node_modules/ajv/dist/compile/codegen/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + var code_1 = require_code(); + var scope_1 = require_scope(); + var code_2 = require_code(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return code_2._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return code_2.str; + } }); + Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() { + return code_2.strConcat; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return code_2.nil; + } }); + Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() { + return code_2.getProperty; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return code_2.stringify; + } }); + Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() { + return code_2.regexpCode; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return code_2.Name; + } }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { enumerable: true, get: function() { + return scope_2.Scope; + } }); + Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() { + return scope_2.ValueScope; + } }); + Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() { + return scope_2.ValueScopeName; + } }); + Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() { + return scope_2.varKinds; + } }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) + return; + if (this.rhs) + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) + return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }; + return addExprNames(names, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + const label = this.label ? ` ${this.label}` : ""; + return `break${label};` + _n; + } + }; + var Throw = class extends Node { + constructor(error2) { + super(); + this.error = error2; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) + nodes.splice(i, 1, ...n); + else if (n) + nodes[i] = n; + else + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) + continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode { + }; + var Else = class extends BlockNode { + }; + Else.kind = "else"; + var If = class _If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) + code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) + return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) + return e instanceof _If ? e : e.nodes; + if (this.nodes.length) + return this; + return new _If(not(cond), e instanceof _If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) + return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) + return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) + addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode { + }; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + const names = addExprNames(super.names, this.from); + return addExprNames(names, this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) + return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + const _async = this.async ? "async " : ""; + return `${_async}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) + code += this.catch.render(opts); + if (this.finally) + code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) + addNames(names, this.catch.names); + if (this.finally) + addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error2) { + super(); + this.error = error2; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { ...opts, _n: opts.lines ? "\n" : "" }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + // returns unique name in the internal scope + name(prefix) { + return this._scope.name(prefix); + } + // reserves unique name in the external scope + scopeName(prefix) { + return this._extScope.name(prefix); + } + // reserves unique name in the external scope and assigns value to it + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set()); + vs.add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + // return code that assigns values in the external scope to the names that are used internally + // (same names that were returned by gen.scopeName or gen.scopeValue) + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) + this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + // `const` declaration (`var` in es5 mode) + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + // `let` declaration with optional assignment (`var` in es5 mode) + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + // `var` declaration with optional assignment + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + // assignment code + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + // `+=` code + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + // appends passed SafeExpr to code or executes Block + code(c) { + if (typeof c == "function") + c(); + else if (c !== code_1.nil) + this._leafNode(new AnyCode(c)); + return this; + } + // returns code for object literal for the passed argument list of key-value pairs + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) + code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) { + this.code(thenBody).else().code(elseBody).endIf(); + } else if (thenBody) { + this.code(thenBody).endIf(); + } else if (elseBody) { + throw new Error('CodeGen: "else" body without "then" body'); + } + return this; + } + // `else if` clause - invalid without `if` or after `else` clauses + elseIf(condition) { + return this._elseNode(new If(condition)); + } + // `else` clause - only valid after `if` or `else if` clauses + else() { + return this._elseNode(new Else()); + } + // end `if` statement (needed if gen.if was used only with condition) + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) + this.code(forBody).endFor(); + return this; + } + // a generic `for` clause (or statement if `forBody` is passed) + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + // `for` statement for a range of values + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + // `for-of` statement (in es5 mode replace with a normal for loop) + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + // `for-in` statement. + // With option `ownProperties` replaced with a `for-of` loop for object keys + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) { + return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + } + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + // end `for` loop + endFor() { + return this._endBlockNode(For); + } + // `label` statement + label(label) { + return this._leafNode(new Label(label)); + } + // `break` statement + break(label) { + return this._leafNode(new Break(label)); + } + // `return` statement + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) + throw new Error('CodeGen: "return" should have one node'); + return this._endBlockNode(Return); + } + // `try` statement + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) + throw new Error('CodeGen: "try" without "catch" and "finally"'); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error2 = this.name("e"); + this._currNode = node.catch = new Catch(error2); + catchCode(error2); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + // `throw` statement + throw(error2) { + return this._leafNode(new Throw(error2)); + } + // start self-balancing block + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) + this.code(body).endBlock(nodeCount); + return this; + } + // end the current self-balancing block + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) + throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) { + throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + } + this._nodes.length = len; + return this; + } + // `function` heading (or definition if funcBody is passed) + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) + this.code(funcBody).endFunc(); + return this; + } + // end function definition + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) { + throw new Error('CodeGen: "else" without "if"'); + } + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) + return replaceName(expr); + if (!canOptimize(expr)) + return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) + c = replaceName(c); + if (c instanceof code_1._Code) + items.push(...c._items); + else + items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) + return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) + names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + var andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + var orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } + } +}); + +// node_modules/ajv/dist/compile/util.js +var require_util = __commonJS({ + "node_modules/ajv/dist/compile/util.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + var codegen_1 = require_codegen(); + var code_1 = require_code(); + function toHash(arr) { + const hash = {}; + for (const item of arr) + hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") + return schema; + if (Object.keys(schema).length === 0) + return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) + return; + if (typeof schema === "boolean") + return; + const rules = self.RULES.keywords; + for (const key in schema) { + if (!rules[key]) + checkStrictMode(it, `unknown keyword: "${key}"`); + } + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (rules[key]) + return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (key !== "$ref" && RULES.all[key]) + return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") + return schema; + if (typeof schema == "string") + return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") + return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) { + for (const x of xs) + f(x); + } else { + f(xs); + } + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) { + gen.assign(to, true); + } else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { ...from, ...to }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) + return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) + setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + var snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type2) { + Type2[Type2["Num"] = 0] = "Num"; + Type2[Type2["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) + return; + msg = `strict mode: ${msg}`; + if (mode === true) + throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; + } +}); + +// node_modules/ajv/dist/compile/names.js +var require_names = __commonJS({ + "node_modules/ajv/dist/compile/names.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var names = { + // validation function arguments + data: new codegen_1.Name("data"), + // data passed to validation function + // args passed from referencing schema + valCxt: new codegen_1.Name("valCxt"), + // validation/data context - should not be used directly, it is destructured to the names below + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + // root data - same as the data passed to the first/top validation function + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + // used to support recursiveRef and dynamicRef + // function scoped variables + vErrors: new codegen_1.Name("vErrors"), + // null or array of validation errors + errors: new codegen_1.Name("errors"), + // counter of validation errors + this: new codegen_1.Name("this"), + // "globals" + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + // JTD serialize/parse name for JSON string and position + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; + } +}); + +// node_modules/ajv/dist/compile/errors.js +var require_errors = __commonJS({ + "node_modules/ajv/dist/compile/errors.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + exports.keywordError = { + message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` + }; + exports.keyword$DataError = { + message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` + }; + function reportError(cxt, error2 = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error2, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) { + addError(gen, errObj); + } else { + returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + } + exports.reportError = reportError; + function reportExtraError(cxt, error2 = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error2, errorPaths); + addError(gen, errObj); + if (!(compositeRule || allErrors)) { + returnErrors(it, names_1.default.vErrors); + } + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + if (errsCount === void 0) + throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) { + gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + var E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + // also used in JTD errors + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error2, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) + return (0, codegen_1._)`{}`; + return errorObject(cxt, error2, errorPaths); + } + function errorObject(cxt, error2, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [ + errorInstancePath(it, errorPaths), + errorSchemaPath(cxt, errorPaths) + ]; + extraErrorProps(cxt, error2, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) { + schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + } + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) { + keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + } + if (opts.verbose) { + keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + } + if (propertyName) + keyValues.push([E.propertyName, propertyName]); + } + } +}); + +// node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = __commonJS({ + "node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + var errors_1 = require_errors(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var boolError = { + message: "boolean schema is false" + }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) { + falseSchemaError(it, false); + } else if (typeof schema == "object" && schema.$async === true) { + gen.return(names_1.default.data); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else { + gen.var(valid, true); + } + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } + } +}); + +// node_modules/ajv/dist/compile/rules.js +var require_rules = __commonJS({ + "node_modules/ajv/dist/compile/rules.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"]; + var jsonTypes = new Set(_jsonTypes); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { type: "number", rules: [] }, + string: { type: "string", rules: [] }, + array: { type: "array", rules: [] }, + object: { type: "object", rules: [] } + }; + return { + types: { ...groups, integer: true, boolean: true, null: true }, + rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; + } +}); + +// node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = __commonJS({ + "node_modules/ajv/dist/compile/validate/applicability.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; + } +}); + +// node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = __commonJS({ + "node_modules/ajv/dist/compile/validate/dataType.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + var rules_1 = require_rules(); + var applicability_1 = require_applicability(); + var errors_1 = require_errors(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var DataType; + (function(DataType2) { + DataType2[DataType2["Correct"] = 0] = "Correct"; + DataType2[DataType2["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + const hasNull = types.includes("null"); + if (hasNull) { + if (schema.nullable === false) + throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) { + throw new Error('"nullable" cannot be used without "type"'); + } + if (schema.nullable === true) + types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts2) { + const types = Array.isArray(ts2) ? ts2 : ts2 ? [ts2] : []; + if (types.every(rules_1.isJSONType)) + return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) + coerceData(it, types, coerceTo); + else + reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") { + gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + } + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) { + if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") { + coerceSpecificType(t); + } + } + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": + gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": + return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: + return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) { + return checkDataType(dataTypes[0], data, strictNums, correct); + } + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else { + cond = codegen_1.nil; + } + if (types.number) + delete types.integer; + for (const t in types) + cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + var typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } + } +}); + +// node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = __commonJS({ + "node_modules/ajv/dist/compile/validate/defaults.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) { + for (const key in properties) { + assignDefault(it, key, properties[key].default); + } + } else if (ty === "array" && Array.isArray(items)) { + items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) + return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") { + condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + } + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } + } +}); + +// node_modules/ajv/dist/vocabularies/code.js +var require_code2 = __commonJS({ + "node_modules/ajv/dist/vocabularies/code.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var names_1 = require_names(); + var util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + // eslint-disable-next-line @typescript-eslint/unbound-method + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) + valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + var newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)); + if (alwaysValid && !it.opts.unevaluated) + return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + const merged = cxt.mergeValidEvaluated(schCxt, schValid); + if (!merged) + gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; + } +}); + +// node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = __commonJS({ + "node_modules/ajv/dist/compile/validate/keyword.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var code_1 = require_code2(); + var errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) + it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate; + const validateRef = useKeyword(gen, keyword, validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) + modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a2; + gen.if((0, codegen_1.not)((_a2 = def.valid) !== null && _a2 !== void 0 ? _a2 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) + throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) + throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { + throw new Error("ajv implementation error"); + } + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) { + throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + } + if (def.validateSchema) { + const valid = def.validateSchema(schema[keyword]); + if (!valid) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") + self.logger.error(msg); + else + throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; + } +}); + +// node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = __commonJS({ + "node_modules/ajv/dist/compile/validate/subschema.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) { + throw new Error('both "keyword" and "schema" passed, only one allowed'); + } + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) { + throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"'); + } + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error('either "keyword" or "schema" must be passed'); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) { + throw new Error('both "data" and "dataProp" passed, only one allowed'); + } + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true); + dataContextProps(nextData); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true); + dataContextProps(nextData); + if (propertyName !== void 0) + subschema.propertyName = propertyName; + } + if (dataTypes) + subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) + subschema.compositeRule = compositeRule; + if (createErrors !== void 0) + subschema.createErrors = createErrors; + if (allErrors !== void 0) + subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; + } +}); + +// node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = __commonJS({ + "node_modules/fast-deep-equal/index.js"(exports, module) { + "use strict"; + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; + } +}); + +// node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = __commonJS({ + "node_modules/json-schema-traverse/index.js"(exports, module) { + "use strict"; + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() { + }; + var post = cb.post || function() { + }; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) { + for (var i = 0; i < sch.length; i++) + _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") { + for (var prop in sch) + _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) { + _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + } +}); + +// node_modules/ajv/dist/compile/resolve.js +var require_resolve = __commonJS({ + "node_modules/ajv/dist/compile/resolve.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + var util_1 = require_util(); + var equal = require_fast_deep_equal(); + var traverse = require_json_schema_traverse(); + var SIMPLE_INLINED = /* @__PURE__ */ new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") + return true; + if (limit === true) + return !hasRef(schema); + if (!limit) + return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + var REF_KEYWORDS = /* @__PURE__ */ new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) + return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) + return true; + if (typeof sch == "object" && hasRef(sch)) + return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") + return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) + continue; + if (typeof schema[key] == "object") { + (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + } + if (count === Infinity) + return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) + id = normalizeId(id); + const p = resolver.parse(id); + return _getFullPath(resolver, p); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + const serialized = resolver.serialize(p); + return serialized.split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + var TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + var ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") + return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) + return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") + innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) + throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") + schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") { + checkAmbiguosRef(sch, schOrRef.schema, ref); + } else if (ref !== normalizeId(fullPath)) { + if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else { + this.refs[ref] = fullPath; + } + } + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) + throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) + throw ambiguos(ref); + } + function ambiguos(ref) { + return new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; + } +}); + +// node_modules/ajv/dist/compile/validate/index.js +var require_validate = __commonJS({ + "node_modules/ajv/dist/compile/validate/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + var boolSchema_1 = require_boolSchema(); + var dataType_1 = require_dataType(); + var applicability_1 = require_applicability(); + var dataType_2 = require_dataType(); + var defaults_1 = require_defaults(); + var keyword_1 = require_keyword(); + var subschema_1 = require_subschema(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + } else { + gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) + gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) + commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) + resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + return; + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") + return !schema; + for (const key in schema) + if (self.RULES.all[key]) + return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) + commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) + return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types); + schemaKeywords(it, types, !checkedTypes, errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) { + self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) { + (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) + it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) + throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) { + gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + } else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) { + gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + } else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) + assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) + gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) + checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) + groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) + return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else { + iterateKeywords(it, group); + } + if (!allErrors) + gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) + (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) { + if ((0, applicability_1.shouldUseRule)(schema, rule)) { + keywordCode(it, rule.keyword, rule.definition, group.type); + } + } + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) + return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) + checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) + return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) { + strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + } + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts2) { + if (ts2.length > 1 && !(ts2.length === 2 && ts2.includes("null"))) { + strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + } + function checkKeywordTypes(it, ts2) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts2, t))) { + strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts2, t) { + return ts2.includes(t) || t === "integer" && ts2.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts2 = []; + for (const t of it.dataTypes) { + if (includesType(withTypes, t)) + ts2.push(t); + else if (withTypes.includes("integer") && t === "number") + ts2.push("integer"); + } + it.dataTypes = ts2; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) { + this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + } else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) { + throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + } + if ("code" in def ? def.trackErrors : def.errors !== false) { + this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) + failAction(); + else + this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) + this.gen.endIf(); + } else { + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) + this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) + this.gen.endIf(); + else + this.gen.else(); + } + fail$data(condition) { + if (!this.$data) + return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + ; + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) + throw new Error('add "trackErrors" to keyword definition'); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) + this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) + Object.assign(this.params, obj); + else + this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) + return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) + gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) + gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + if (!(schemaCode instanceof codegen_1.Name)) + throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) + return; + if (it.props !== true && schemaCxt.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + } + if (it.items !== true && schemaCxt.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) { + def.code(cxt, ruleType); + } else if (cxt.$data && def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } else if ("macro" in def) { + (0, keyword_1.macroKeywordCode)(cxt, def); + } else if (def.compile || def.validate) { + (0, keyword_1.funcKeywordCode)(cxt, def); + } + } + var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") + return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) + throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) + throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) + throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) + throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) + return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) { + if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; + } +}); + +// node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = __commonJS({ + "node_modules/ajv/dist/runtime/validation_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; + } +}); + +// node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = __commonJS({ + "node_modules/ajv/dist/compile/ref_error.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; + } +}); + +// node_modules/ajv/dist/compile/index.js +var require_compile = __commonJS({ + "node_modules/ajv/dist/compile/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + var codegen_1 = require_codegen(); + var validation_error_1 = require_validation_error(); + var names_1 = require_names(); + var resolve_1 = require_resolve(); + var util_1 = require_util(); + var validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") + schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) + return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties }); + let _ValidationError; + if (sch.$async) { + _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + } + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + // TODO can its length be used as dataLevel if nil is removed? + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) + sourceCode = this.opts.code.process(sourceCode, sch); + const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode); + const validate = makeValidate(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) + validate.$async = true; + if (this.opts.code.source === true) { + validate.source = { validateName, validateCode, scopeValues: gen._values }; + } + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) + validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) + this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) + return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) + _sch = new SchemaEnv({ schema, schemaId, root, baseId }); + } + if (_sch === void 0) + return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) + return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) { + if (sameSchemaEnv(sch, schEnv)) + return sch; + } + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") + ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) { + return getJsonPointer.call(this, p, root); + } + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") + return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") + return; + if (!schOrRef.validate) + compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ schema, schemaId, root, baseId }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") + return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") + return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) + return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) { + baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ schema, schemaId, root, baseId }); + if (env.schema !== env.root.schema) + return env; + return void 0; + } + } +}); + +// node_modules/ajv/dist/refs/data.json +var require_data = __commonJS({ + "node_modules/ajv/dist/refs/data.json"(exports, module) { + module.exports = { + $id: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + description: "Meta-schema for $data reference (JSON AnySchema extension proposal)", + type: "object", + required: ["$data"], + properties: { + $data: { + type: "string", + anyOf: [{ format: "relative-json-pointer" }, { format: "json-pointer" }] + } + }, + additionalProperties: false + }; + } +}); + +// node_modules/fast-uri/lib/utils.js +var require_utils = __commonJS({ + "node_modules/fast-uri/lib/utils.js"(exports, module) { + "use strict"; + var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + var isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + var isPort = RegExp.prototype.test.bind(/^\d*$/u); + var isHexPair = RegExp.prototype.test.bind(/^[\da-f]{2}$/iu); + var isUnreserved = RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu); + var isPathCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u); + var isQueryFragmentCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u); + var isUserinfoCharacter = RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u); + var BYTE_HEX = new Array(256); + { + const HEX_DIGITS = "0123456789ABCDEF"; + for (let i = 0; i < 256; i++) { + BYTE_HEX[i] = "%" + HEX_DIGITS[i >> 4] + HEX_DIGITS[i & 15]; + } + } + function percentEncodeNonAscii(cp) { + if (cp < 2048) { + return BYTE_HEX[192 | cp >> 6] + BYTE_HEX[128 | cp & 63]; + } + if (cp < 65536) { + return BYTE_HEX[224 | cp >> 12] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; + } + return BYTE_HEX[240 | cp >> 18] + BYTE_HEX[128 | cp >> 12 & 63] + BYTE_HEX[128 | cp >> 6 & 63] + BYTE_HEX[128 | cp & 63]; + } + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) { + continue; + } + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) { + return ""; + } + acc += input[i]; + } + return acc; + } + var isHextet = RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/); + var isIPvFuture = RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/); + var isZoneCharacter = RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/); + var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + function isZoneIdentifier(zone) { + if (zone.length === 0) return false; + for (let i = 0; i < zone.length; i++) { + if (isZoneCharacter(zone[i])) continue; + if (zone[i] === "%" && i + 2 < zone.length && isHexPair(zone.slice(i + 1, i + 3))) { + i += 2; + continue; + } + return false; + } + return true; + } + function compressIPv6ZeroRun(hextets) { + let bestStart = -1; + let bestLength = 0; + let runStart = -1; + let runLength = 0; + for (let i = 0; i < hextets.length; i++) { + if (hextets[i] === "0") { + if (runStart === -1) runStart = i; + runLength++; + if (runLength > bestLength) { + bestLength = runLength; + bestStart = runStart; + } + } else { + runStart = -1; + runLength = 0; + } + } + if (bestLength < 2) return hextets.join(":"); + const head = hextets.slice(0, bestStart).join(":"); + const tail = hextets.slice(bestStart + bestLength).join(":"); + return head + "::" + tail; + } + function normalizeIPv6Address(input) { + const compression = input.indexOf("::"); + if (compression !== -1 && input.indexOf("::", compression + 1) !== -1) return void 0; + const left = compression === -1 ? input.split(":") : input.slice(0, compression).split(":"); + const right = compression === -1 ? [] : input.slice(compression + 2).split(":"); + if (compression !== -1) { + if (left.length === 1 && left[0] === "") left.length = 0; + if (right.length === 1 && right[0] === "") right.length = 0; + } + const parts = left.concat(right); + let hextetCount = 0; + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + if (part === "") return void 0; + if (part.indexOf(".") !== -1) { + if (i !== parts.length - 1 || compression !== -1 && right.length === 0 || !isIPv4(part)) return void 0; + hextetCount += 2; + continue; + } + if (!isHextet(part)) return void 0; + parts[i] = parseInt(part, 16).toString(16); + hextetCount++; + } + if (compression === -1) { + if (hextetCount !== 8) return void 0; + return compressIPv6ZeroRun(parts); + } + if (hextetCount >= 8) return void 0; + const expanded = parts.slice(0, left.length); + for (let i = hextetCount; i < 8; i++) expanded.push("0"); + for (let i = left.length; i < parts.length; i++) expanded.push(parts[i]); + return compressIPv6ZeroRun(expanded); + } + function normalizeIPv6(host) { + const bracketed = host[0] === "[" && host[host.length - 1] === "]"; + const hasBracket = host[0] === "[" || host[host.length - 1] === "]"; + if (hasBracket && !bracketed) return { host, isIPV6: false, error: true }; + let input = bracketed ? host.slice(1, -1) : host; + if (bracketed && isIPvFuture(input)) { + input = input.toLowerCase(); + return { host: `[${input}]`, escapedHost: input, isIPV6: false, isIPVFuture: true }; + } + if (findToken(input, ":") < 2) { + return { host, isIPV6: false, error: bracketed }; + } + let zoneIdentifier = ""; + const zoneSeparator = input.indexOf("%"); + if (zoneSeparator !== -1) { + const separatorLength = input.slice(zoneSeparator, zoneSeparator + 3).toLowerCase() === "%25" ? 3 : 1; + zoneIdentifier = input.slice(zoneSeparator + separatorLength); + if (!isZoneIdentifier(zoneIdentifier)) return { host, isIPV6: false, error: true }; + input = input.slice(0, zoneSeparator); + } + const address = normalizeIPv6Address(input); + if (address === void 0) return { host, isIPV6: false, error: true }; + return { + host: address + (zoneIdentifier ? "%" + zoneIdentifier : ""), + escapedHost: address + (zoneIdentifier ? "%25" + zoneIdentifier : ""), + isIPV6: true + }; + } + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) { + if (str[i] === token) ind++; + } + return ind; + } + function removeDotSegments(path21) { + let input = path21; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) { + if (input === ".") { + break; + } else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + } else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") { + break; + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) { + output.pop(); + } + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) { + output.pop(); + } + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + var HOST_DELIMS = { "@": "%40", "/": "%2F", "?": "%3F", "#": "%23", ":": "%3A" }; + var HOST_DELIM_RE = /[@/?#:]/g; + var HOST_DELIM_NO_COLON_RE = /[@/?#]/g; + function reescapeHostDelimiters(host, isIP) { + const re = isIP ? HOST_DELIM_NO_COLON_RE : HOST_DELIM_RE; + re.lastIndex = 0; + return host.replace(re, (ch) => HOST_DELIMS[ch]); + } + function normalizePercentEncoding(input, decodeUnreserved = false) { + if (input.indexOf("%") === -1) { + return input; + } + let output = ""; + for (let i = 0; i < input.length; i++) { + if (input[i] === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + const normalizedHex = hex.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (decodeUnreserved && isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + output += input[i]; + } + return output; + } + function normalizePathEncoding(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + const normalizedHex = hex.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (decoded !== "." && isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + if (isPathCharacter(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function serializePathEncoding(input, pathNoScheme = false) { + let output = ""; + let firstSegment = pathNoScheme && input[0] !== "/"; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + output += "%" + hex.toUpperCase(); + i += 2; + continue; + } + } + if (ch === "/") { + firstSegment = false; + } + if (isPathCharacter(ch) && (ch !== ":" || !firstSegment)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function encodeComponent(input, isAllowed) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + output += "%" + hex.toUpperCase(); + i += 2; + continue; + } + } + if (isAllowed(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function encodeUserinfo(input) { + return encodeComponent(input, isUserinfoCharacter); + } + function encodeQuery(input) { + return encodeComponent(input, isQueryFragmentCharacter); + } + function encodeFragment(input) { + return encodeComponent(input, isQueryFragmentCharacter); + } + function isEscapeSafe(cp) { + return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 42 || cp === 43 || cp === 45 || cp === 46 || cp === 47 || cp === 64 || cp === 95; + } + function normalizeQueryFragmentEncoding(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + const ch = input[i]; + if (ch === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + const normalizedHex = hex.toUpperCase(); + const decoded = String.fromCharCode(parseInt(normalizedHex, 16)); + if (isUnreserved(decoded)) { + output += decoded; + } else { + output += "%" + normalizedHex; + } + i += 2; + continue; + } + } + if (isQueryFragmentCharacter(ch)) { + output += ch; + } else { + const code = input.charCodeAt(i); + if (code < 128) { + output += isEscapeSafe(code) ? ch : BYTE_HEX[code]; + } else if (code < 55296 || code > 57343) { + output += percentEncodeNonAscii(code); + } else if (code <= 56319 && i + 1 < input.length) { + const low = input.charCodeAt(i + 1); + if (low >= 56320 && low <= 57343) { + output += percentEncodeNonAscii(65536 + (code - 55296 << 10) + (low - 56320)); + i++; + } else { + output += percentEncodeNonAscii(65533); + } + } else { + output += percentEncodeNonAscii(65533); + } + } + } + return output; + } + function escapePreservingEscapes(input) { + let output = ""; + for (let i = 0; i < input.length; i++) { + if (input[i] === "%" && i + 2 < input.length) { + const hex = input.slice(i + 1, i + 3); + if (isHexPair(hex)) { + output += "%" + hex.toUpperCase(); + i += 2; + continue; + } + } + output += escape(input[i]); + } + return output; + } + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(encodeUserinfo(component.userinfo)); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = component.host; + if (!isIPv4(host)) { + let ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 !== true && ipV6res.isIPVFuture !== true) { + host = normalizePercentEncoding(host, true); + ipV6res = normalizeIPv6(host); + } + if (ipV6res.isIPV6 === true || ipV6res.isIPVFuture === true) { + host = `[${ipV6res.escapedHost}]`; + } else { + host = reescapeHostDelimiters(host, false); + } + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + const port = String(component.port); + if (!isPort(port)) { + throw new TypeError("URI port is malformed."); + } + uriTokens.push(":"); + uriTokens.push(port); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + reescapeHostDelimiters, + normalizePercentEncoding, + normalizePathEncoding, + serializePathEncoding, + normalizeQueryFragmentEncoding, + encodeUserinfo, + encodeQuery, + encodeFragment, + escapePreservingEscapes, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; + } +}); + +// node_modules/fast-uri/lib/schemes.js +var require_schemes = __commonJS({ + "node_modules/fast-uri/lib/schemes.js"(exports, module) { + "use strict"; + var { isUUID } = require_utils(); + var URN_REG = /^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu; + var supportedSchemeNames = ( + /** @type {const} */ + [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ] + ); + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf( + /** @type {*} */ + name + ) !== -1; + } + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) { + return true; + } else if (wsComponent.secure === false) { + return false; + } else if (wsComponent.scheme) { + return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + } else { + return false; + } + } + function httpParse(component) { + if (!component.host) { + component.error = component.error || "HTTP URIs must have a host."; + } + return component; + } + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") { + component.port = void 0; + } + if (!component.path) { + component.path = "/"; + } + return component; + } + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") { + wsComponent.port = void 0; + } + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const queryIndex = wsComponent.resourceName.indexOf("?"); + const path21 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex); + wsComponent.path = path21 && path21 !== "/" ? path21 : void 0; + wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1); + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches && matches[0] === urnComponent.path) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + urnComponent.path = void 0; + if (schemeHandler) { + urnComponent = schemeHandler.parse(urnComponent, options); + } + } else { + urnComponent.error = urnComponent.error || "URN can not be parsed."; + } + return urnComponent; + } + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) { + throw new Error("URN without nid cannot be serialized"); + } + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const urnScheme = `${scheme}:${options.nid || nid}`; + const schemeHandler = getSchemeHandler(urnScheme); + if (schemeHandler) { + urnComponent = schemeHandler.serialize(urnComponent, options); + } + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) { + uuidComponent.error = uuidComponent.error || "UUID is not valid."; + } + return uuidComponent; + } + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + var http2 = ( + /** @type {SchemeHandler} */ + { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + } + ); + var https = ( + /** @type {SchemeHandler} */ + { + scheme: "https", + domainHost: http2.domainHost, + parse: httpParse, + serialize: httpSerialize + } + ); + var ws = ( + /** @type {SchemeHandler} */ + { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + } + ); + var wss = ( + /** @type {SchemeHandler} */ + { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + } + ); + var urn = ( + /** @type {SchemeHandler} */ + { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + } + ); + var urnuuid = ( + /** @type {SchemeHandler} */ + { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + } + ); + var SCHEMES = ( + /** @type {Record} */ + { + http: http2, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + } + ); + Object.setPrototypeOf(SCHEMES, null); + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[ + /** @type {SchemeName} */ + scheme + ] || SCHEMES[ + /** @type {SchemeName} */ + scheme.toLowerCase() + ]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; + } +}); + +// node_modules/fast-uri/index.js +var require_fast_uri = __commonJS({ + "node_modules/fast-uri/index.js"(exports, module) { + "use strict"; + var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizePercentEncoding, normalizePathEncoding, serializePathEncoding, normalizeQueryFragmentEncoding, encodeQuery, encodeFragment, reescapeHostDelimiters, isIPv4, nonSimpleDomain } = require_utils(); + var { SCHEMES, getSchemeHandler } = require_schemes(); + var VALID_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*$/u; + var MALFORMED_SCHEME_ERROR = "URI scheme is malformed."; + function decodeValidScheme(scheme) { + const decodedScheme = unescape(String(scheme)); + if (!VALID_SCHEME.test(decodedScheme)) { + throw new TypeError(MALFORMED_SCHEME_ERROR); + } + return decodedScheme; + } + function normalize(uri, options) { + if (typeof uri === "string") { + uri = /** @type {T} */ + normalizeString(uri, options); + } else if (typeof uri === "object") { + uri = /** @type {T} */ + parse3(serialize(uri, options), options); + } + return uri; + } + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const { + parsed: baseParsed, + malformedAuthorityOrPort: baseMalformed, + malformedPercentEncoding: baseMalformedPercentEncoding, + malformedSchemeSpecific: baseMalformedSchemeSpecific, + malformedHost: baseMalformedHost, + malformedScheme: baseMalformedScheme + } = parseWithStatus(baseURI, schemelessOptions); + const { + parsed: relativeParsed, + malformedAuthorityOrPort: relativeMalformed, + malformedPercentEncoding: relativeMalformedPercentEncoding, + malformedSchemeSpecific: relativeMalformedSchemeSpecific, + malformedHost: relativeMalformedHost, + malformedScheme: relativeMalformedScheme + } = parseWithStatus(relativeURI, schemelessOptions); + if (baseMalformed || relativeMalformed || baseMalformedPercentEncoding || relativeMalformedPercentEncoding || baseMalformedSchemeSpecific || relativeMalformedSchemeSpecific || baseMalformedHost || relativeMalformedHost || baseMalformedScheme || relativeMalformedScheme) { + throw new Error(baseParsed.error || relativeParsed.error || "URI is malformed."); + } + const resolved = resolveComponent(baseParsed, relativeParsed, schemelessOptions, true); + const resolvedSchemeHandler = getSchemeHandler(options && options.scheme || resolved.scheme); + const resolvedHost = resolved.host; + const resolvedHostIsIP = resolvedHost !== void 0 && resolvedHost !== "" && (isIPv4(resolvedHost) || normalizeIPv6(resolvedHost).isIPV6); + canonicalizeHost(resolved, options || {}, resolvedSchemeHandler, resolvedHostIsIP); + const encodedASCIIHost = resolvedHost && resolvedHost.indexOf("%") !== -1 && !new RegExp("\\P{ASCII}", "u").test(resolvedHost); + if (resolved.error && !encodedASCIIHost) { + throw new Error(resolved.error); + } + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + function resolveComponent(base, relative, options, skipNormalization) { + const target = {}; + if (!skipNormalization) { + base = parse3(serialize(base, options), options); + relative = parse3(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path[0] === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + function equal(uriA, uriB, options) { + const normalizedA = normalizeComparableURI(uriA, options); + const normalizedB = normalizeComparableURI(uriB, options); + return normalizedA !== void 0 && normalizedB !== void 0 && normalizedA === normalizedB; + } + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + if (component.scheme) { + component.scheme = decodeValidScheme(component.scheme); + } + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + const hasAuthority = component.userinfo !== void 0 || component.host !== void 0 || component.port !== void 0; + const pathNoScheme = !options.skipEscape && component.scheme === void 0 && !hasAuthority; + if (component.path !== void 0) { + if (!options.skipEscape) { + component.path = serializePathEncoding(component.path, pathNoScheme); + } else { + component.path = normalizePercentEncoding(component.path); + } + } + if (options.reference !== "suffix" && component.scheme) { + component.scheme = decodeValidScheme(component.scheme); + uriTokens.push(component.scheme, ":"); + } + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") { + uriTokens.push("/"); + } + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (pathNoScheme) { + s = serializePathEncoding(s, true); + } + if (authority === void 0 && s[0] === "/" && s[1] === "/") { + s = "/%2F" + s.slice(2); + } + uriTokens.push(s); + } + if (component.query !== void 0) { + uriTokens.push("?", encodeQuery(component.query)); + } + if (component.fragment !== void 0) { + uriTokens.push("#", encodeFragment(component.fragment)); + } + return uriTokens.join(""); + } + var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + var AUTHORITY_PREFIX = /^(?:[^#/:?]+:)?\/\/([^/?#]*)/; + var AUTHORITY_INTRODUCER_REGION = /^(?:[^#/:?]+:)?([/\\\t\n\r]*)/; + function getParseError(parsed, matches) { + if (matches[2] !== void 0 && parsed.path && parsed.path[0] !== "/") { + return 'URI path must start with "/" when authority is present.'; + } + if (typeof parsed.port === "number" && (parsed.port < 0 || parsed.port > 65535)) { + return "URI port is malformed."; + } + return void 0; + } + function hasMalformedPercentEncoding(component) { + if (component === void 0) return false; + let percent = component.indexOf("%"); + while (percent !== -1) { + if (percent + 2 >= component.length || !/^[\da-f]{2}$/iu.test(component.slice(percent + 1, percent + 3))) { + return true; + } + percent = component.indexOf("%", percent + 3); + } + return false; + } + function isIPLiteral(host) { + return host[0] === "[" && host[host.length - 1] === "]"; + } + function hasMalformedComponentPercentEncoding(matches) { + const host = matches[4]; + return hasMalformedPercentEncoding(matches[3]) || host !== void 0 && !isIPLiteral(host) && hasMalformedPercentEncoding(host) || hasMalformedPercentEncoding(matches[6]) || hasMalformedPercentEncoding(matches[7]) || hasMalformedPercentEncoding(matches[8]); + } + function canonicalizeHost(parsed, options, schemeHandler, isIP) { + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport) && parsed.host && !isIPLiteral(parsed.host) && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) { + try { + parsed.host = new URL("http://" + parsed.host).hostname; + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + return true; + } + } + return false; + } + function parseWithStatus(uri, opts) { + const options = Object.assign({}, opts); + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let malformedAuthorityOrPort = false; + let malformedPercentEncoding = false; + let malformedSchemeSpecific = false; + let malformedHost = false; + let malformedIPLiteral = false; + let malformedScheme = false; + let isIP = false; + if (options.reference === "suffix") { + if (options.scheme) { + uri = options.scheme + ":" + uri; + } else { + uri = "//" + uri; + } + } + const authorityMatch = uri.match(AUTHORITY_PREFIX); + if (authorityMatch !== null && authorityMatch[1].indexOf("\\") !== -1) { + parsed.error = "URI authority must not contain a literal backslash."; + malformedAuthorityOrPort = true; + } + const introducerMatch = uri.match(AUTHORITY_INTRODUCER_REGION); + if (introducerMatch !== null) { + const region = introducerMatch[1]; + const normalizedRegion = region.replace(/[\t\n\r]/g, ""); + if (normalizedRegion.length >= 2) { + if (normalizedRegion.slice(0, 2) !== "//") { + parsed.error = parsed.error || "URI authority must not contain a literal backslash."; + malformedAuthorityOrPort = true; + } else if (region.length !== normalizedRegion.length) { + parsed.error = parsed.error || "URI authority introducer must not contain whitespace."; + malformedAuthorityOrPort = true; + } + } + } + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (parsed.scheme !== void 0) { + const decodedScheme = unescape(parsed.scheme); + if (VALID_SCHEME.test(decodedScheme)) { + parsed.scheme = decodedScheme.toLowerCase(); + } else { + parsed.error = parsed.error || MALFORMED_SCHEME_ERROR; + malformedScheme = true; + } + } + malformedPercentEncoding = hasMalformedComponentPercentEncoding(matches); + if (malformedPercentEncoding) { + parsed.error = parsed.error || "URI contains malformed percent-encoding."; + } + if (isNaN(parsed.port)) { + parsed.port = matches[5]; + } + const parseError = getParseError(parsed, matches); + if (parseError !== void 0) { + parsed.error = parsed.error || parseError; + malformedAuthorityOrPort = true; + } + if (parsed.host) { + const ipv4result = isIPv4(parsed.host); + if (ipv4result === false) { + const bracketedIPLiteral = isIPLiteral(parsed.host); + const hasIPLiteralBracket = parsed.host.indexOf("[") !== -1 || parsed.host.indexOf("]") !== -1; + const ipv6result = normalizeIPv6(parsed.host); + isIP = ipv6result.isIPV6 || ipv6result.isIPVFuture === true; + malformedIPLiteral = hasIPLiteralBracket && (!bracketedIPLiteral || ipv6result.error === true); + parsed.host = isIP ? ipv6result.host : ipv6result.host.toLowerCase(); + if (malformedIPLiteral) { + parsed.error = parsed.error || "URI host is malformed."; + malformedAuthorityOrPort = true; + } + } else { + isIP = true; + } + } + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) { + parsed.reference = "same-document"; + } else if (parsed.scheme === void 0) { + parsed.reference = "relative"; + } else if (parsed.fragment === void 0) { + parsed.reference = "absolute"; + } else { + parsed.reference = "uri"; + } + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) { + parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + } + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!malformedIPLiteral) { + malformedHost = canonicalizeHost(parsed, options, schemeHandler, isIP); + } + if (uri.indexOf("%") !== -1 && parsed.host !== void 0 && !malformedIPLiteral) { + let host = isIP ? parsed.host : normalizePercentEncoding(parsed.host, true); + if (!isIP) { + host = normalizePercentEncoding(host.toLowerCase()); + } + parsed.host = reescapeHostDelimiters(host, isIP); + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (parsed.path) { + parsed.path = normalizePathEncoding(parsed.path); + } + if (parsed.query) { + parsed.query = normalizeQueryFragmentEncoding(parsed.query); + } + if (parsed.fragment) { + parsed.fragment = normalizeQueryFragmentEncoding(parsed.fragment); + } + } + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(parsed, options); + if (schemeHandler === SCHEMES.urn && parsed.nid === void 0) { + malformedSchemeSpecific = true; + } + } + } else { + parsed.error = parsed.error || "URI can not be parsed."; + } + return { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme }; + } + function parse3(uri, opts) { + return parseWithStatus(uri, opts).parsed; + } + function normalizeString(uri, opts) { + return normalizeStringWithStatus(uri, opts).normalized; + } + function normalizeStringWithStatus(uri, opts) { + const { parsed, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = parseWithStatus(uri, opts); + return { + normalized: malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? uri : serialize(parsed, opts), + malformedAuthorityOrPort, + malformedPercentEncoding, + malformedSchemeSpecific, + malformedHost, + malformedScheme + }; + } + function normalizeComparableURI(uri, opts) { + if (typeof uri !== "string" && typeof uri !== "object") { + return void 0; + } + let value; + try { + value = typeof uri === "string" ? uri : serialize(uri, opts); + } catch { + return void 0; + } + const { normalized, malformedAuthorityOrPort, malformedPercentEncoding, malformedSchemeSpecific, malformedHost, malformedScheme } = normalizeStringWithStatus(value, opts); + return malformedAuthorityOrPort || malformedPercentEncoding || malformedSchemeSpecific || malformedHost || malformedScheme ? void 0 : normalized; + } + var fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse: parse3 + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; + } +}); + +// node_modules/ajv/dist/runtime/uri.js +var require_uri = __commonJS({ + "node_modules/ajv/dist/runtime/uri.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var uri = require_fast_uri(); + uri.code = 'require("ajv/dist/runtime/uri").default'; + exports.default = uri; + } +}); + +// node_modules/ajv/dist/core.js +var require_core = __commonJS({ + "node_modules/ajv/dist/core.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + var ref_error_1 = require_ref_error(); + var rules_1 = require_rules(); + var compile_1 = require_compile(); + var codegen_2 = require_codegen(); + var resolve_1 = require_resolve(); + var dataType_1 = require_dataType(); + var util_1 = require_util(); + var $dataRefSchema = require_data(); + var uri_1 = require_uri(); + var defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"]; + var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + var removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: '"nullable" keyword is supported by default.', + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: '"uniqueItems" keyword is always validated.', + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + var deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: '"minLength"/"maxLength" account for unicode characters by default.' + }; + var MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv2 = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = /* @__PURE__ */ Object.create(null); + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { ...opts, ...requiredOptions(opts) }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) + addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) + addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") + this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) + this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) + throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else { + v = this.compile(schemaKeyRef); + } + const valid = v(data); + if (!("$async" in v)) + this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") { + throw new Error("options.loadSchema should be a function"); + } + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) { + await runCompileAsync.call(this, { $ref }, true); + } + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) + throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) { + throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) + await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) + this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) + return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + // Adds schema to the instance + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) + this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") { + throw new Error(`schema ${schemaId} must be string`); + } + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + // Add schema that will be used to validate other schemas + // options in META_IGNORE_OPTIONS are alway set to false + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + // Validate schema against its meta-schema + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") + return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") { + throw new Error("$schema must be a string"); + } + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") + this.logger.error(message); + else + throw new Error(message); + } + return valid; + } + // Get compiled schema by `key` or `ref`. + // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") + keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ schema: {}, schemaId }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) + return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + // Remove cached schema(s). + // If no parameter is passed all schemas but meta-schemas are removed. + // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") + this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: + throw new Error("ajv.removeSchema: invalid parameter"); + } + } + // add "vocabulary" - a collection of keywords + addVocabulary(definitions) { + for (const def of definitions) + this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) { + throw new Error("addKeywords: keyword must be string or non-empty array"); + } + } else { + throw new Error("invalid addKeywords parameters"); + } + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + // Remove keyword + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) + group.rules.splice(i, 1); + } + return this; + } + // Add format + addFormat(name, format) { + if (typeof format == "string") + format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) + return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) + keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") + continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) + keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") { + delete schemas[keyRef]; + } else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") { + id = schema[schemaId]; + } else { + if (this.opts.jtd) + throw new Error("schema must be object"); + else if (typeof schema != "boolean") + throw new Error("schema must be object or boolean"); + } + let sch = this._cache.get(schema); + if (sch !== void 0) + return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ schema, schemaId, meta, baseId, localRefs }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) + this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) + this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) { + throw new Error(`schema with key or id "${id}" already exists`); + } + } + _compileSchemaEnv(sch) { + if (sch.meta) + this._compileMetaSchema(sch); + else + compile_1.compileSchema.call(this, sch); + if (!sch.validate) + throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv2.ValidationError = validation_error_1.default; + Ajv2.MissingRefError = ref_error_1.default; + exports.default = Ajv2; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) + this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) + return; + if (Array.isArray(optsSchemas)) + this.addSchema(optsSchemas); + else + for (const key in optsSchemas) + this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) + this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) + def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) + delete metaOpts[opt]; + return metaOpts; + } + var noLogs = { log() { + }, warn() { + }, error() { + } }; + function getLogger(logger) { + if (logger === false) + return noLogs; + if (logger === void 0) + return console; + if (logger.log && logger.warn && logger.error) + return logger; + throw new Error("logger must implement log, warn and error methods"); + } + var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) + throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) + throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) + return; + if (def.$data && !("code" in def || "validate" in def)) { + throw new Error('$data keyword must have "code" or "validate" function'); + } + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) + throw new Error('keyword with "post" flag cannot have "type"'); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) + return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) + addBeforeRule.call(this, ruleGroup, rule, definition.before); + else + ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 ? void 0 : _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) { + ruleGroup.rules.splice(i, 0, rule); + } else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) + return; + if (def.$data && this.opts.$data) + metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + var $dataRef = { + $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" + }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } + } +}); + +// node_modules/ajv/dist/vocabularies/core/id.js +var require_id = __commonJS({ + "node_modules/ajv/dist/vocabularies/core/id.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var def = { + keyword: "id", + code() { + throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID'); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = __commonJS({ + "node_modules/ajv/dist/vocabularies/core/ref.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + var ref_error_1 = require_ref_error(); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var compile_1 = require_compile(); + var util_1 = require_util(); + var def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) + return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) + throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) + return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) + return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + const v = getValidate(cxt, sch); + callRef(cxt, v, sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) + callAsyncRef(); + else + callSyncRef(); + function callAsyncRef() { + if (!env.$async) + throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) + gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) + gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) + return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) { + if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) { + it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + } + if (it.items !== true) { + if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) { + it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + } + exports.callRef = callRef; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/core/index.js +var require_core2 = __commonJS({ + "node_modules/ajv/dist/vocabularies/core/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var id_1 = require_id(); + var ref_1 = require_ref(); + var core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error2 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + var def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error2 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }; + var def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = __commonJS({ + "node_modules/ajv/dist/runtime/ucs2length.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) + pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default'; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var ucs2length_1 = require_ucs2length(); + var error2 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var util_1 = require_util(); + var codegen_1 = require_codegen(); + var error2 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }; + var def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: error2, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error2 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/required.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }; + var def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: error2, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) + return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) + allErrorsMode(); + else + exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) { + if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + } + function allErrorsMode() { + if (useLoop || $data) { + cxt.block$data(codegen_1.nil, loopAllRequired); + } else { + for (const prop of schema) { + (0, code_1.checkReportMissingProp)(cxt, prop); + } + } + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error2 = { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }; + var def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: error2, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/runtime/equal.js +var require_equal = __commonJS({ + "node_modules/ajv/dist/runtime/equal.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var equal = require_fast_deep_equal(); + equal.code = 'require("ajv/dist/runtime/equal").default'; + exports.default = equal; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var dataType_1 = require_dataType(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error2 = { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }; + var def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: error2, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) + return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ i, j }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) + gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/const.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error2 = { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }; + var def = { + keyword: "const", + $data: true, + error: error2, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") { + cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + } else { + cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var equal_1 = require_equal(); + var error2 = { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }; + var def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: error2, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) + throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation = __commonJS({ + "node_modules/ajv/dist/vocabularies/validation/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var limitNumber_1 = require_limitNumber(); + var multipleOf_1 = require_multipleOf(); + var limitLength_1 = require_limitLength(); + var pattern_1 = require_pattern(); + var limitProperties_1 = require_limitProperties(); + var required_1 = require_required(); + var limitItems_1 = require_limitItems(); + var uniqueItems_1 = require_uniqueItems(); + var const_1 = require_const(); + var enum_1 = require_enum(); + var validation = [ + // number + limitNumber_1.default, + multipleOf_1.default, + // string + limitLength_1.default, + pattern_1.default, + // object + limitProperties_1.default, + required_1.default, + // array + limitItems_1.default, + uniqueItems_1.default, + // any + { keyword: "type", schemaType: ["string", "array"] }, + { keyword: "nullable", schemaType: "boolean" }, + const_1.default, + enum_1.default + ]; + exports.default = validation; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: error2, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas'); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid); + if (!it.allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "array", "boolean"], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) + return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) { + it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + } + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var items_1 = require_items(); + var def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + var additionalItems_1 = require_additionalItems(); + var error2 = { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }; + var def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: error2, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + if (prefixItems) + (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }; + var def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: error2, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else { + min = 1; + } + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ min, max }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) + cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) { + validateItems(valid, () => gen.if(valid, () => gen.break())); + } else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) + gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) { + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + } else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) + gen.assign(valid, true); + else + gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var code_1 = require_code2(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + // TODO change to reference + }; + var def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") + continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) + return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) + continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) { + gen.if(hasProperty, () => { + for (const depProp of deps) { + (0, code_1.checkReportMissingProp)(cxt, depProp); + } + }); + } else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) + continue; + gen.if( + (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), + () => { + const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, + () => gen.var(valid, true) + // TODO var + ); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }; + var def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: error2, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) + return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) + gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var names_1 = require_names(); + var util_1 = require_util(); + var error2 = { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }; + var def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: error2, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + if (!errsCount) + throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) + return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) + additionalPropertyCode(key); + else + gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) { + definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + } else { + definedProp = codegen_1.nil; + } + if (patProps.length) { + definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + } + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) + gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) { + Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + } + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var validate_1 = require_validate(); + var code_1 = require_code2(); + var util_1 = require_util(); + var additionalProperties_1 = require_additionalProperties(); + var def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) { + additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + } + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) { + it.definedProperties.add(prop); + } + if (it.opts.unevaluated && allProps.length && it.props !== true) { + it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + } + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) + return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) { + applyPropertySchema(prop); + } else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) + gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var util_2 = require_util(); + var def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) { + return; + } + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) { + it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + } + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) + checkMatchingProperties(pat); + if (it.allErrors) { + validateProperties(pat); + } else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) { + if (new RegExp(pat).test(prop)) { + (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + } + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) { + cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + } + if (it.opts.unevaluated && props !== true) { + gen.assign((0, codegen_1._)`${props}[${key}]`, true); + } else if (!alwaysValid && !it.allErrors) { + gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var code_1 = require_code2(); + var def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: code_1.validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }; + var def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: error2, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) + return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) { + gen.var(schValid, true); + } else { + schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + } + if (i > 0) { + gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + } + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) + cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + if (!Array.isArray(schema)) + throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) + return; + const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var util_1 = require_util(); + var error2 = { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }; + var def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: error2, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) { + (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored'); + } + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) + return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) { + gen.if(schValid, validateClause("then")); + } else { + gen.if((0, codegen_1.not)(schValid), validateClause("else")); + } + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) + gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else + cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var util_1 = require_util(); + var def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) + (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator = __commonJS({ + "node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var additionalItems_1 = require_additionalItems(); + var prefixItems_1 = require_prefixItems(); + var items_1 = require_items(); + var items2020_1 = require_items2020(); + var contains_1 = require_contains(); + var dependencies_1 = require_dependencies(); + var propertyNames_1 = require_propertyNames(); + var additionalProperties_1 = require_additionalProperties(); + var properties_1 = require_properties(); + var patternProperties_1 = require_patternProperties(); + var not_1 = require_not(); + var anyOf_1 = require_anyOf(); + var oneOf_1 = require_oneOf(); + var allOf_1 = require_allOf(); + var if_1 = require_if(); + var thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + // any + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + // object + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) + applicator.push(prefixItems_1.default, items2020_1.default); + else + applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; + } +}); + +// node_modules/ajv/dist/vocabularies/format/format.js +var require_format = __commonJS({ + "node_modules/ajv/dist/vocabularies/format/format.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var error2 = { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }; + var def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: error2, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) + return; + if ($data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) + return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) + return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) + cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) { + return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`]; + } + return ["string", fmtDef, fmt]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) + throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/vocabularies/format/index.js +var require_format2 = __commonJS({ + "node_modules/ajv/dist/vocabularies/format/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var format_1 = require_format(); + var format = [format_1.default]; + exports.default = format; + } +}); + +// node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = __commonJS({ + "node_modules/ajv/dist/vocabularies/metadata.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; + } +}); + +// node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = __commonJS({ + "node_modules/ajv/dist/vocabularies/draft7.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var core_1 = require_core2(); + var validation_1 = require_validation(); + var applicator_1 = require_applicator(); + var format_1 = require_format2(); + var metadata_1 = require_metadata(); + var draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; + } +}); + +// node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = __commonJS({ + "node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError2) { + DiscrError2["Tag"] = "tag"; + DiscrError2["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); + } +}); + +// node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = __commonJS({ + "node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var codegen_1 = require_codegen(); + var types_1 = require_types(); + var compile_1 = require_compile(); + var ref_error_1 = require_ref_error(); + var util_1 = require_util(); + var error2 = { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }; + var def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: error2, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) { + throw new Error("discriminator: requires discriminator option"); + } + const tagName = schema.propertyName; + if (typeof tagName != "string") + throw new Error("discriminator: requires propertyName"); + if (schema.mapping) + throw new Error("discriminator: mapping is not supported"); + if (!oneOf) + throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) + sch = sch.schema; + if (sch === void 0) + throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") { + throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + } + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) + throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required: required2 }) { + return Array.isArray(required2) && required2.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) { + addMapping(sch.const, i); + } else if (sch.enum) { + for (const tagValue of sch.enum) { + addMapping(tagValue, i); + } + } else { + throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) { + throw new Error(`discriminator: "${tagName}" values must be unique strings`); + } + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def; + } +}); + +// node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = __commonJS({ + "node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) { + module.exports = { + $schema: "http://json-schema.org/draft-07/schema#", + $id: "http://json-schema.org/draft-07/schema#", + title: "Core schema meta-schema", + definitions: { + schemaArray: { + type: "array", + minItems: 1, + items: { $ref: "#" } + }, + nonNegativeInteger: { + type: "integer", + minimum: 0 + }, + nonNegativeIntegerDefault0: { + allOf: [{ $ref: "#/definitions/nonNegativeInteger" }, { default: 0 }] + }, + simpleTypes: { + enum: ["array", "boolean", "integer", "null", "number", "object", "string"] + }, + stringArray: { + type: "array", + items: { type: "string" }, + uniqueItems: true, + default: [] + } + }, + type: ["object", "boolean"], + properties: { + $id: { + type: "string", + format: "uri-reference" + }, + $schema: { + type: "string", + format: "uri" + }, + $ref: { + type: "string", + format: "uri-reference" + }, + $comment: { + type: "string" + }, + title: { + type: "string" + }, + description: { + type: "string" + }, + default: true, + readOnly: { + type: "boolean", + default: false + }, + examples: { + type: "array", + items: true + }, + multipleOf: { + type: "number", + exclusiveMinimum: 0 + }, + maximum: { + type: "number" + }, + exclusiveMaximum: { + type: "number" + }, + minimum: { + type: "number" + }, + exclusiveMinimum: { + type: "number" + }, + maxLength: { $ref: "#/definitions/nonNegativeInteger" }, + minLength: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + pattern: { + type: "string", + format: "regex" + }, + additionalItems: { $ref: "#" }, + items: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }], + default: true + }, + maxItems: { $ref: "#/definitions/nonNegativeInteger" }, + minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + uniqueItems: { + type: "boolean", + default: false + }, + contains: { $ref: "#" }, + maxProperties: { $ref: "#/definitions/nonNegativeInteger" }, + minProperties: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, + required: { $ref: "#/definitions/stringArray" }, + additionalProperties: { $ref: "#" }, + definitions: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + properties: { + type: "object", + additionalProperties: { $ref: "#" }, + default: {} + }, + patternProperties: { + type: "object", + additionalProperties: { $ref: "#" }, + propertyNames: { format: "regex" }, + default: {} + }, + dependencies: { + type: "object", + additionalProperties: { + anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }] + } + }, + propertyNames: { $ref: "#" }, + const: true, + enum: { + type: "array", + items: true, + minItems: 1, + uniqueItems: true + }, + type: { + anyOf: [ + { $ref: "#/definitions/simpleTypes" }, + { + type: "array", + items: { $ref: "#/definitions/simpleTypes" }, + minItems: 1, + uniqueItems: true + } + ] + }, + format: { type: "string" }, + contentMediaType: { type: "string" }, + contentEncoding: { type: "string" }, + if: { $ref: "#" }, + then: { $ref: "#" }, + else: { $ref: "#" }, + allOf: { $ref: "#/definitions/schemaArray" }, + anyOf: { $ref: "#/definitions/schemaArray" }, + oneOf: { $ref: "#/definitions/schemaArray" }, + not: { $ref: "#" } + }, + default: true + }; + } +}); + +// node_modules/ajv/dist/ajv.js +var require_ajv = __commonJS({ + "node_modules/ajv/dist/ajv.js"(exports, module) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + var core_1 = require_core(); + var draft7_1 = require_draft7(); + var discriminator_1 = require_discriminator(); + var draft7MetaSchema = require_json_schema_draft_07(); + var META_SUPPORT_DATA = ["/properties"]; + var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv2 = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) + this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) + return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv2; + module.exports = exports = Ajv2; + module.exports.Ajv = Ajv2; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() { + return validate_1.KeywordCxt; + } }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { enumerable: true, get: function() { + return codegen_1._; + } }); + Object.defineProperty(exports, "str", { enumerable: true, get: function() { + return codegen_1.str; + } }); + Object.defineProperty(exports, "stringify", { enumerable: true, get: function() { + return codegen_1.stringify; + } }); + Object.defineProperty(exports, "nil", { enumerable: true, get: function() { + return codegen_1.nil; + } }); + Object.defineProperty(exports, "Name", { enumerable: true, get: function() { + return codegen_1.Name; + } }); + Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() { + return codegen_1.CodeGen; + } }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() { + return validation_error_1.default; + } }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() { + return ref_error_1.default; + } }); + } +}); + +// node_modules/ajv-formats/dist/formats.js +var require_formats = __commonJS({ + "node_modules/ajv-formats/dist/formats.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { validate, compare }; + } + exports.fullFormats = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: fmtDef(date3, compareDate), + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + // duration: https://tools.ietf.org/html/rfc3339#appendix-A + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + // uri-template: https://tools.ietf.org/html/rfc6570 + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + // For the source: https://gist.github.com/dperini/729294 + // For test cases: https://mathiasbynens.be/demo/url-regex + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types + // byte: https://github.com/miguelmota/is-base64 + byte, + // signed 32 bit integer + int32: { type: "number", validate: validateInt32 }, + // signed 64 bit integer + int64: { type: "number", validate: validateInt64 }, + // C-type float + float: { type: "number", validate: validateNumber }, + // C-type double + double: { type: "number", validate: validateNumber }, + // hint to the UI to hide input strings + password: true, + // unchecked string payload + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation') + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + function date3(str) { + const matches = DATE.exec(str); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) + return void 0; + if (d1 > d2) + return 1; + if (d1 < d2) + return -1; + return 0; + } + var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time3(str) { + const matches = TIME.exec(str); + if (!matches) + return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) + return false; + if (hr <= 23 && min <= 59 && sec < 60) + return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) + return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) + return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) + return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) + return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) + return 1; + if (t1 < t2) + return -1; + return 0; + } + var DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time3 = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date3(dateTime[0]) && time3(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) + return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) + return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) + return void 0; + return res || compareTime(t1, t2); + } + var NOT_URI_FRAGMENT = /\/|:/; + var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + var MIN_INT32 = -(2 ** 31); + var MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + var Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } + } +}); + +// node_modules/ajv-formats/dist/limit.js +var require_limit = __commonJS({ + "node_modules/ajv-formats/dist/limit.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + var ajv_1 = require_ajv(); + var codegen_1 = require_codegen(); + var ops = codegen_1.operators; + var KWDs = { + formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT }, + formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT }, + formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE }, + formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE } + }; + var error2 = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error: error2, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) + return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) + validate$DataFormat(); + else + validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) + return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") { + throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + } + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + var formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; + } +}); + +// node_modules/ajv-formats/dist/index.js +var require_dist = __commonJS({ + "node_modules/ajv-formats/dist/index.js"(exports, module) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var formats_1 = require_formats(); + var limit_1 = require_limit(); + var codegen_1 = require_codegen(); + var fullName = new codegen_1.Name("fullFormats"); + var fastName = new codegen_1.Name("fastFormats"); + var formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + const list = opts.formats || formats_1.formatNames; + addFormats(ajv, list, formats, exportName); + if (opts.keywords) + (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats; + const f = formats[name]; + if (!f) + throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs22, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; + for (const f of list) + ajv.addFormat(f, fs22[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; + } +}); + +// src/daemon.ts +import fs21 from "node:fs"; +import path20 from "node:path"; +import { fileURLToPath as fileURLToPath3 } from "node:url"; + +// node_modules/zod/v3/external.js +var external_exports = {}; +__export(external_exports, { + BRAND: () => BRAND, + DIRTY: () => DIRTY, + EMPTY_PATH: () => EMPTY_PATH, + INVALID: () => INVALID, + NEVER: () => NEVER, + OK: () => OK, + ParseStatus: () => ParseStatus, + Schema: () => ZodType, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBigInt: () => ZodBigInt, + ZodBoolean: () => ZodBoolean, + ZodBranded: () => ZodBranded, + ZodCatch: () => ZodCatch, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodEffects: () => ZodEffects, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNativeEnum: () => ZodNativeEnum, + ZodNever: () => ZodNever, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodParsedType: () => ZodParsedType, + ZodPipeline: () => ZodPipeline, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSchema: () => ZodType, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodSymbol: () => ZodSymbol, + ZodTransformer: () => ZodEffects, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + addIssueToContext: () => addIssueToContext, + any: () => anyType, + array: () => arrayType, + bigint: () => bigIntType, + boolean: () => booleanType, + coerce: () => coerce, + custom: () => custom, + date: () => dateType, + datetimeRegex: () => datetimeRegex, + defaultErrorMap: () => en_default, + discriminatedUnion: () => discriminatedUnionType, + effect: () => effectsType, + enum: () => enumType, + function: () => functionType, + getErrorMap: () => getErrorMap, + getParsedType: () => getParsedType, + instanceof: () => instanceOfType, + intersection: () => intersectionType, + isAborted: () => isAborted, + isAsync: () => isAsync, + isDirty: () => isDirty, + isValid: () => isValid, + late: () => late, + lazy: () => lazyType, + literal: () => literalType, + makeIssue: () => makeIssue, + map: () => mapType, + nan: () => nanType, + nativeEnum: () => nativeEnumType, + never: () => neverType, + null: () => nullType, + nullable: () => nullableType, + number: () => numberType, + object: () => objectType, + objectUtil: () => objectUtil, + oboolean: () => oboolean, + onumber: () => onumber, + optional: () => optionalType, + ostring: () => ostring, + pipeline: () => pipelineType, + preprocess: () => preprocessType, + promise: () => promiseType, + quotelessJson: () => quotelessJson, + record: () => recordType, + set: () => setType, + setErrorMap: () => setErrorMap, + strictObject: () => strictObjectType, + string: () => stringType, + symbol: () => symbolType, + transformer: () => effectsType, + tuple: () => tupleType, + undefined: () => undefinedType, + union: () => unionType, + unknown: () => unknownType, + util: () => util, + void: () => voidType +}); + +// node_modules/zod/v3/helpers/util.js +var util; +(function(util2) { + util2.assertEqual = (_) => { + }; + function assertIs2(_arg) { + } + util2.assertIs = assertIs2; + function assertNever2(_x) { + throw new Error(); + } + util2.assertNever = assertNever2; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => { + const keys = []; + for (const key in object3) { + if (Object.prototype.hasOwnProperty.call(object3, key)) { + keys.push(key); + } + } + return keys; + }; + util2.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues2(array2, separator = " | ") { + return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues2; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; + +// node_modules/zod/v3/ZodError.js +var ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +var ZodError = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error2) => { + for (const issue2 of error2.issues) { + if (issue2.code === "invalid_union") { + issue2.unionErrors.map(processError); + } else if (issue2.code === "invalid_return_type") { + processError(issue2.returnTypeError); + } else if (issue2.code === "invalid_arguments") { + processError(issue2.argumentsError); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue2.path.length) { + const el = issue2.path[i]; + const terminal = i === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues) => { + const error2 = new ZodError(issues); + return error2; +}; + +// node_modules/zod/v3/locales/en.js +var errorMap = (issue2, _ctx) => { + let message; + switch (issue2.code) { + case ZodIssueCode.invalid_type: + if (issue2.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue2.expected}, received ${issue2.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue2.validation === "object") { + if ("includes" in issue2.validation) { + message = `Invalid input: must include "${issue2.validation.includes}"`; + if (typeof issue2.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`; + } + } else if ("startsWith" in issue2.validation) { + message = `Invalid input: must start with "${issue2.validation.startsWith}"`; + } else if ("endsWith" in issue2.validation) { + message = `Invalid input: must end with "${issue2.validation.endsWith}"`; + } else { + util.assertNever(issue2.validation); + } + } else if (issue2.validation !== "regex") { + message = `Invalid ${issue2.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue2.type === "array") + message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`; + else if (issue2.type === "string") + message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`; + else if (issue2.type === "number") + message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "bigint") + message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`; + else if (issue2.type === "date") + message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue2.type === "array") + message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`; + else if (issue2.type === "string") + message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`; + else if (issue2.type === "number") + message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "bigint") + message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`; + else if (issue2.type === "date") + message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue2.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue2); + } + return { message }; +}; +var en_default = errorMap; + +// node_modules/zod/v3/errors.js +var overrideErrorMap = en_default; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} + +// node_modules/zod/v3/helpers/parseUtil.js +var makeIssue = (params) => { + const { data, path: path21, errorMaps, issueData } = params; + const fullPath = [...path21, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage2 = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map of maps) { + errorMessage2 = map(fullIssue, { data, defaultError: errorMessage2 }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage2 + }; +}; +var EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue2 = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_default ? void 0 : en_default + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue2); +} +var ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +}; +var INVALID = Object.freeze({ + status: "aborted" +}); +var DIRTY = (value) => ({ status: "dirty", value }); +var OK = (value) => ({ status: "valid", value }); +var isAborted = (x) => x.status === "aborted"; +var isDirty = (x) => x.status === "dirty"; +var isValid = (x) => x.status === "valid"; +var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + +// node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); + +// node_modules/zod/v3/types.js +var ParseInputLazyPath = class { + constructor(parent, value, path21, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path21; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +}; +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error2 = new ZodError(ctx.common.issues); + this._error = error2; + return this._error; + } + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +var ZodType = class { + get description() { + return this._def.description; + } + _getType(input) { + return getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return ctx || { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + }; + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent + } + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check2, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check2(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check2, refinementData) { + return this._refinement((val, ctx) => { + if (!check2(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform2) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform: transform2 } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}; +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[0-9a-z]+$/; +var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var nanoidRegex = /^[a-z0-9_-]{21}$/i; +var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var emojiRegex; +var ipv4Regex = /^(?:(?: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])$/; +var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; +var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +var dateRegexSource = `((\\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])))`; +var dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version2) { + if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { + return true; + } + if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base642 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base642)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } +} +function isValidCidr(ip, version2) { + if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +var ZodString = class _ZodString2 extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.length < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.length > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "length") { + const tooBig = input.data.length > check2.value; + const tooSmall = input.data.length < check2.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "string", + inclusive: true, + exact: true, + message: check2.message + }); + } + status.dirty(); + } + } else if (check2.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "url") { + try { + new URL(input.data); + } catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "regex") { + check2.regex.lastIndex = 0; + const testResult = check2.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "trim") { + input.data = input.data.trim(); + } else if (check2.kind === "includes") { + if (!input.data.includes(check2.value, check2.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check2.value, position: check2.position }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } else if (check2.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } else if (check2.kind === "startsWith") { + if (!input.data.startsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check2.value }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "endsWith") { + if (!input.data.endsWith(check2.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check2.value }, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "datetime") { + const regex = datetimeRegex(check2); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "time") { + const regex = timeRegex(check2); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "ip") { + if (!isValidIP(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "jwt") { + if (!isValidJWT(input.data, check2.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "cidr") { + if (!isValidCidr(input.data, check2.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); + } + _addCheck(check2) { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, check2] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString2({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +var ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check2 of this._def.checks) { + if (check2.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check2.value, + type: "number", + inclusive: check2.inclusive, + exact: false, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (floatSafeRemainder(input.data, check2.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check2) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check2] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } catch { + return this._getInvalidInput(input); + } + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "max") { + const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check2.value, + inclusive: check2.inclusive, + message: check2.message + }); + status.dirty(); + } + } else if (check2.kind === "multipleOf") { + if (input.data % check2.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check2.value, + message: check2.message + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check2) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check2] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodDate = class _ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check2 of this._def.checks) { + if (check2.kind === "min") { + if (input.data.getTime() < check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check2.message, + inclusive: true, + exact: false, + minimum: check2.value, + type: "date" + }); + status.dirty(); + } + } else if (check2.kind === "max") { + if (input.data.getTime() > check2.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check2.message, + inclusive: true, + exact: false, + maximum: check2.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check2); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()) + }; + } + _addCheck(check2) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check2] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +}; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); +}; +var ZodSymbol = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); +}; +var ZodUndefined = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); +}; +var ZodNull = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); +}; +var ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); +}; +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +}; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); +}; +var ZodNever = class extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; + } +}; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); +}; +var ZodVoid = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input.data); + } +}; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); +}; +var ZodArray = class _ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; + } +} +var ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue2, ctx) => { + const defaultError = this._def.errorMap?.(issue2, ctx).message ?? ctx.defaultError; + if (issue2.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new _ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +}; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +var ZodUnion = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [void 0]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [void 0, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}; +var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} +var ZodIntersection = class extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } +}; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); +}; +var ZodTuple = class _ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}; +var ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); +}; +var ZodSet = class _ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); +}; +var ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error2) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error2 + } + }); + } + function makeReturnsIssue(returns, error2) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error2 + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error2 = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error2.addIssue(makeArgsIssue(args, e)); + throw error2; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error2.addIssue(makeReturnsIssue(result, e)); + throw error2; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}; +var ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); +}; +var ZodLiteral = class extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class _ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return _ZodEnum.create(values, { + ...this._def, + ...newDef + }); + } + exclude(values, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); + } +}; +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); +}; +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } +}; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); +}; +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util.assertNever(effect); + } +}; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); +}; +ZodEffects.createWithPreprocess = (preprocess2, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess2 }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); +}; +var ZodOptional = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 === ZodParsedType.undefined) { + return OK(void 0); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); +}; +var ZodNullable = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); +}; +var ZodDefault = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); +}; +var ZodCatch = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); +}; +var ZodNaN = class extends ZodType { + _parse(input) { + const parsedType2 = this._getType(input); + if (parsedType2 !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +}; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); +}; +var BRAND = Symbol("zod_brand"); +var ZodBranded = class extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } +}; +var ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a, b) { + return new _ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}; +var ZodReadonly = class extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +}; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); +}; +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom(check2, _params = {}, fatal) { + if (check2) + return ZodAny.create().superRefine((data, ctx) => { + const r = check2(data); + if (r instanceof Promise) { + return r.then((r2) => { + if (!r2) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +var late = { + object: ZodObject.lazycreate +}; +var ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data) => data instanceof cls, params); +var stringType = ZodString.create; +var numberType = ZodNumber.create; +var nanType = ZodNaN.create; +var bigIntType = ZodBigInt.create; +var booleanType = ZodBoolean.create; +var dateType = ZodDate.create; +var symbolType = ZodSymbol.create; +var undefinedType = ZodUndefined.create; +var nullType = ZodNull.create; +var anyType = ZodAny.create; +var unknownType = ZodUnknown.create; +var neverType = ZodNever.create; +var voidType = ZodVoid.create; +var arrayType = ZodArray.create; +var objectType = ZodObject.create; +var strictObjectType = ZodObject.strictCreate; +var unionType = ZodUnion.create; +var discriminatedUnionType = ZodDiscriminatedUnion.create; +var intersectionType = ZodIntersection.create; +var tupleType = ZodTuple.create; +var recordType = ZodRecord.create; +var mapType = ZodMap.create; +var setType = ZodSet.create; +var functionType = ZodFunction.create; +var lazyType = ZodLazy.create; +var literalType = ZodLiteral.create; +var enumType = ZodEnum.create; +var nativeEnumType = ZodNativeEnum.create; +var promiseType = ZodPromise.create; +var effectsType = ZodEffects.create; +var optionalType = ZodOptional.create; +var nullableType = ZodNullable.create; +var preprocessType = ZodEffects.createWithPreprocess; +var pipelineType = ZodPipeline.create; +var ostring = () => stringType().optional(); +var onumber = () => numberType().optional(); +var oboolean = () => booleanType().optional(); +var coerce = { + string: (arg) => ZodString.create({ ...arg, coerce: true }), + number: (arg) => ZodNumber.create({ ...arg, coerce: true }), + boolean: (arg) => ZodBoolean.create({ + ...arg, + coerce: true + }), + bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), + date: (arg) => ZodDate.create({ ...arg, coerce: true }) +}; +var NEVER = INVALID; + +// node_modules/zod/v4/core/core.js +var NEVER2 = Object.freeze({ + status: "aborted" +}); +// @__NO_SIDE_EFFECTS__ +function $constructor(name, initializer3, params) { + function init(inst, def) { + var _a; + Object.defineProperty(inst, "_zod", { + value: inst._zod ?? {}, + enumerable: false + }); + (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set()); + inst._zod.traits.add(name); + initializer3(inst, def); + for (const k in _.prototype) { + if (!(k in inst)) + Object.defineProperty(inst, k, { value: _.prototype[k].bind(inst) }); + } + inst._zod.constr = _; + inst._zod.def = def; + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a = inst._zod).deferred ?? (_a.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +var $brand = Symbol("zod_brand"); +var $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +}; +var globalConfig = {}; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +// node_modules/zod/v4/core/util.js +var util_exports = {}; +__export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder2, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType2, + getSizableOrigin: () => getSizableOrigin, + isObject: () => isObject, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + omit: () => omit, + optionalKeys: () => optionalKeys, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + stringifyPrimitive: () => stringifyPrimitive, + unwrapMessage: () => unwrapMessage +}); +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { +} +function assertNever(_x) { + throw new Error(); +} +function assert(_) { +} +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); + return values; +} +function joinValues(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + } + }; +} +function nullish(input) { + return input === null || input === void 0; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder2(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +function defineLazy(object3, key, getter) { + const set = false; + Object.defineProperty(object3, key, { + get() { + if (!set) { + const value = getter(); + object3[key] = value; + return value; + } + throw new Error("cached value already set"); + }, + set(v) { + Object.defineProperty(object3, key, { + value: v + // configurable: true, + }); + }, + configurable: true + }); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); +} +function getElementAtPath(obj, path21) { + if (!path21) + return obj; + return path21.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +var captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { +}; +function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +var allowsEval = cached(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (isObject(o) === false) + return false; + const ctor = o.constructor; + if (ctor === void 0) + return true; + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +var getParsedType2 = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); +var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + } + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); +} +var NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] +}; +var BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] +}; +function pick(schema, mask) { + const newShape = {}; + const currDef = schema._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + return clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [] + }); +} +function omit(schema, mask) { + const newShape = { ...schema._zod.def.shape }; + const currDef = schema._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + return clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [] + }); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const def = { + ...schema._zod.def, + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + checks: [] + // delete existing checks + }; + return clone(schema, def); +} +function merge(a, b) { + return clone(a, { + ...a._zod.def, + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + catchall: b._zod.def.catchall, + checks: [] + // delete existing checks + }); +} +function partial(Class2, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + return clone(schema, { + ...schema._zod.def, + shape, + checks: [] + }); +} +function required(Class2, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } + return clone(schema, { + ...schema._zod.def, + shape, + // optional: [], + checks: [] + }); +} +function aborted(x, startIndex = 0) { + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) + return true; + } + return false; +} +function prefixIssues(path21, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path21); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue(iss, ctx, config3) { + const full = { ...iss, path: iss.path ?? [] }; + if (!iss.message) { + const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config3.customError?.(iss)) ?? unwrapMessage(config3.localeError?.(iss)) ?? "Invalid input"; + full.message = message; + } + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj).filter(([k, _]) => { + return Number.isNaN(Number.parseInt(k, 10)); + }).map((el) => el[1]); +} +var Class = class { + constructor(..._args) { + } +}; + +// node_modules/zod/v4/core/errors.js +var initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + Object.defineProperty(inst, "message", { + get() { + return JSON.stringify(def, jsonStringifyReplacer, 2); + }, + enumerable: true + // configurable: false, + }); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); +}; +var $ZodError = $constructor("$ZodError", initializer); +var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); +function flattenError(error2, mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error2.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error2, _mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error3) => { + for (const issue2 of error3.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues })); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue2.path.length) { + const el = issue2.path[i]; + const terminal = i === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(error2); + return fieldErrors; +} + +// node_modules/zod/v4/core/parse.js +var _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; +}; +var _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; +}; +var _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; +}; +var safeParse = /* @__PURE__ */ _safeParse($ZodRealError); +var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; +}; +var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); + +// node_modules/zod/v4/core/regexes.js +var cuid = /^[cC][^\s-]{8,}$/; +var cuid2 = /^[0-9a-z]+$/; +var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +var xid = /^[0-9a-vA-V]{20}$/; +var ksuid = /^[A-Za-z0-9]{27}$/; +var nanoid = /^[a-zA-Z0-9_-]{21}$/; +var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +var guid = /^([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})$/; +var uuid = (version2) => { + if (!version2) + return /^([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)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +var ipv4 = /^(?:(?: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])$/; +var ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; +var cidrv4 = /^((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])$/; +var cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +var base64url = /^[A-Za-z0-9_-]*$/; +var hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +var e164 = /^\+(?:[0-9]){6,14}[0-9]$/; +var dateSource = `(?:(?:\\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])))`; +var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +function datetime(args) { + const time3 = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-]\\d{2}:\\d{2})`); + const timeRegex2 = `${time3}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex2})$`); +} +var string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +var integer = /^\d+$/; +var number = /^-?\d+(?:\.\d+)?/i; +var boolean = /true|false/i; +var _null = /null/i; +var lowercase = /^[^A-Z]*$/; +var uppercase = /^[^a-z]*$/; + +// node_modules/zod/v4/core/checks.js +var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +var numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" +}; +var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_big", + maximum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_small", + minimum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + var _a; + (_a = inst2._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort + }); + } else { + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inst + }); + } + }; +}); +var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...def.pattern ? { pattern: def.pattern.toString() } : {}, + inst, + continue: !def.abort + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { + }); +}); +var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +// node_modules/zod/v4/core/doc.js +var Doc = class { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + return new F(...args, lines.join("\n")); + } +}; + +// node_modules/zod/v4/core/versions.js +var version = { + major: 4, + minor: 0, + patch: 0 +}; + +// node_modules/zod/v4/core/schemas.js +var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks2, ctx) => { + let isAborted2 = aborted(payload); + let asyncResult; + for (const ch of checks2) { + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } else if (isAborted2) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted2) + isAborted2 = aborted(payload, currLen); + }); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted2) + isAborted2 = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + inst._zod.run = (payload, ctx) => { + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + inst["~standard"] = { + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_) { + return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); + } + }, + vendor: "zod", + version: 1 + }; +}); +var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } catch (_2) { + } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }; + const v = versionMap[def.version]; + if (v === void 0) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const orig = payload.value; + const url = new URL(orig); + const href = url.href; + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + } + if (!orig.endsWith("/") && href.endsWith("/")) { + payload.value = href.slice(0, -1); + } else { + payload.value = href; + } + return; + } catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); +}); +var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); +}); +var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time(def)); + $ZodStringFormat.init(inst, def); +}); +var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = `ipv4`; + }); +}); +var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = `ipv6`; + }); + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const [address, prefix] = payload.value.split("/"); + try { + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; +}); +function isValidBase64(data) { + if (data === "") + return true; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; + } catch { + return false; + } +} +var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.contentEncoding = "base64"; + }); + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +function isValidBase64URL(data) { + if (!base64url.test(data)) + return false; + const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "="); + return isValidBase64(padded); +} +var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.contentEncoding = "base64url"; + }); + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +function isValidJWT2(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } catch { + return false; + } +} +var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT2(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort + }); + }; +}); +var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } catch (_) { + } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} + }); + return payload; + }; +}); +var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); +}); +var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } catch (_) { + } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = /* @__PURE__ */ new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst + }); + return payload; + }; +}); +var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; +}); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleArrayResult(result2, payload, i))); + } else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +function handleObjectResult(result, final, key) { + if (result.issues.length) { + final.issues.push(...prefixIssues(key, result.issues)); + } + final.value[key] = result.value; +} +function handleOptionalObjectResult(result, final, key, input) { + if (result.issues.length) { + if (input[key] === void 0) { + if (key in input) { + final.value[key] = void 0; + } else { + final.value[key] = result.value; + } + } else { + final.issues.push(...prefixIssues(key, result.issues)); + } + } else if (result.value === void 0) { + if (key in input) + final.value[key] = void 0; + } else { + final.value[key] = result.value; + } +} +var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { + $ZodType.init(inst, def); + const _normalized = cached(() => { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!(def.shape[k] instanceof $ZodType)) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + shape: def.shape, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; + }); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k = esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = /* @__PURE__ */ Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + doc.write(`const newResult = {}`); + for (const key of normalized.keys) { + if (normalized.optionalKeys.has(key)) { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + const k = esc(key); + doc.write(` + if (${id}.issues.length) { + if (input[${k}] === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${id}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}], + })) + ); + } + } else if (${id}.value === undefined) { + if (${k} in input) newResult[${k}] = undefined; + } else { + newResult[${k}] = ${id}.value; + } + `); + } else { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(` + if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}] + })));`); + doc.write(`newResult[${esc(key)}] = ${id}.value`); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject2 = isObject; + const jit = !globalConfig.jitless; + const allowsEval2 = allowsEval; + const fastEnabled = jit && allowsEval2.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject2(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + } else { + payload.value = {}; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; + if (r instanceof Promise) { + proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key))); + } else if (isOptional) { + handleOptionalObjectResult(r, payload, key, input); + } else { + handleObjectResult(r, payload, key); + } + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + const unrecognized = []; + const keySet = value.keySet; + const _catchall = catchall._zod; + const t = _catchall.def.type; + for (const key of Object.keys(input)) { + if (keySet.has(key)) + continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handleObjectResult(r2, payload, key))); + } else { + handleObjectResult(r, payload, key); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + return final; +} +var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return void 0; + }); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return void 0; + }); + inst._zod.parse = (payload, ctx) => { + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleUnionResults(results2, payload, inst, ctx); + }); + }; +}); +var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = /* @__PURE__ */ new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = cached(() => { + const opts = def.options; + const map = /* @__PURE__ */ new Map(); + for (const o of opts) { + const values = o._zod.propValues[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + if (def.unionFallback) { + return _super(payload, ctx); + } + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + input, + path: [def.discriminator], + inst + }); + return payload; + }; +}); +var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left2, right2]) => { + return handleIntersectionResults(payload, left2, right2); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function mergeValues2(a, b) { + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues2(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues2(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath] + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + if (left.issues.length) { + result.issues.push(...left.issues); + } + if (right.issues.length) { + result.issues.push(...right.issues); + } + if (aborted(result)) + return result; + const merged = mergeValues2(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + if (def.keyType._zod.values) { + const values = def.keyType._zod.values; + payload.value = {}; + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[key] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!values.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); + } + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + origin: "record", + code: "invalid_key", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + payload.value[keyResult.value] = keyResult.value; + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + inst._zod.values = new Set(values); + inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst + }); + return payload; + }; +}); +var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.values = new Set(def.values); + inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst + }); + return payload; + }; +}); +var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const _out = def.transform(payload.value, payload); + if (_ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output2) => { + payload.value = output2; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}); +var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === void 0) { + payload.value = def.defaultValue; + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult(result2, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return payload; +} +var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== void 0)) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult(result2, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + } + return payload; +} +var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.value; + if (result2.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }); + } + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }; +}); +var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + inst._zod.parse = (payload, ctx) => { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult(left2, def, ctx)); + } + return handlePipeResult(left, def, ctx); + }; +}); +function handlePipeResult(left, def, ctx) { + if (aborted(left)) { + return left; + } + return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); +} +var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + // incorporates params.error into issue reporting + path: [...inst._zod.def.path ?? []], + // incorporates params.error into issue reporting + continue: !inst._zod.def.abort + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(issue(_iss)); + } +} + +// node_modules/zod/v4/locales/en.js +var parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}; +var error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + 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", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue2.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue2.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue2.origin}`; + default: + return `Invalid input`; + } + }; +}; +function en_default2() { + return { + localeError: error() + }; +} + +// node_modules/zod/v4/core/registries.js +var $output = Symbol("ZodOutput"); +var $input = Symbol("ZodInput"); +var $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new Map(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + if (this._idmap.has(meta.id)) { + throw new Error(`ID ${meta.id} already exists in the registry`); + } + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = /* @__PURE__ */ new Map(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + const p = schema._zod.parent; + if (p) { + const pm = { ...this.get(p) ?? {} }; + delete pm.id; + return { ...pm, ...this._map.get(schema) }; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +}; +function registry() { + return new $ZodRegistry(); +} +var globalRegistry = /* @__PURE__ */ registry(); + +// node_modules/zod/v4/core/api.js +function _string(Class2, params) { + return new Class2({ + type: "string", + ...normalizeParams(params) + }); +} +function _email(Class2, params) { + return new Class2({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _guid(Class2, params) { + return new Class2({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _uuid(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _uuidv4(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); +} +function _uuidv6(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); +} +function _uuidv7(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); +} +function _url(Class2, params) { + return new Class2({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _emoji2(Class2, params) { + return new Class2({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _nanoid(Class2, params) { + return new Class2({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _cuid(Class2, params) { + return new Class2({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _cuid2(Class2, params) { + return new Class2({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _ulid(Class2, params) { + return new Class2({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _xid(Class2, params) { + return new Class2({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _ksuid(Class2, params) { + return new Class2({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _ipv4(Class2, params) { + return new Class2({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _ipv6(Class2, params) { + return new Class2({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _cidrv4(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _cidrv6(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _base64(Class2, params) { + return new Class2({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _base64url(Class2, params) { + return new Class2({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _e164(Class2, params) { + return new Class2({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _jwt(Class2, params) { + return new Class2({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); +} +function _isoDateTime(Class2, params) { + return new Class2({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); +} +function _isoDate(Class2, params) { + return new Class2({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); +} +function _isoTime(Class2, params) { + return new Class2({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); +} +function _isoDuration(Class2, params) { + return new Class2({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); +} +function _number(Class2, params) { + return new Class2({ + type: "number", + checks: [], + ...normalizeParams(params) + }); +} +function _int(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); +} +function _boolean(Class2, params) { + return new Class2({ + type: "boolean", + ...normalizeParams(params) + }); +} +function _null2(Class2, params) { + return new Class2({ + type: "null", + ...normalizeParams(params) + }); +} +function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); +} +function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); +} +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false + }); +} +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true + }); +} +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value + }); +} +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); + return ch; +} +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); +} +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); +} +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); +} +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); +} +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); +} +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); +} +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); +} +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); +} +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); +} +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +function _trim() { + return _overwrite((input) => input.trim()); +} +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +function _array(Class2, element, params) { + return new Class2({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params) + }); +} +function _custom(Class2, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...norm + }); + return schema; +} +function _refine(Class2, fn, _params) { + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) + }); + return schema; +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js +function isZ4Schema(s) { + const schema = s; + return !!schema._zod; +} +function safeParse2(schema, data) { + if (isZ4Schema(schema)) { + const result2 = safeParse(schema, data); + return result2; + } + const v3Schema = schema; + const result = v3Schema.safeParse(data); + return result; +} +function getObjectShape(schema) { + if (!schema) + return void 0; + let rawShape; + if (isZ4Schema(schema)) { + const v4Schema = schema; + rawShape = v4Schema._zod?.def?.shape; + } else { + const v3Schema = schema; + rawShape = v3Schema.shape; + } + if (!rawShape) + return void 0; + if (typeof rawShape === "function") { + try { + return rawShape(); + } catch { + return void 0; + } + } + return rawShape; +} +function getLiteralValue(schema) { + if (isZ4Schema(schema)) { + const v4Schema = schema; + const def2 = v4Schema._zod?.def; + if (def2) { + if (def2.value !== void 0) + return def2.value; + if (Array.isArray(def2.values) && def2.values.length > 0) { + return def2.values[0]; + } + } + } + const v3Schema = schema; + const def = v3Schema._def; + if (def) { + if (def.value !== void 0) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + const directValue = schema.value; + if (directValue !== void 0) + return directValue; + return void 0; +} + +// node_modules/zod/v4/classic/iso.js +var iso_exports = {}; +__export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date2, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 +}); +var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); +} +var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function date2(params) { + return _isoDate(ZodISODate, params); +} +var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function time2(params) { + return _isoTime(ZodISOTime, params); +} +var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function duration2(params) { + return _isoDuration(ZodISODuration, params); +} + +// node_modules/zod/v4/classic/errors.js +var initializer2 = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper) + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper) + // enumerable: false, + }, + addIssue: { + value: (issue2) => inst.issues.push(issue2) + // enumerable: false, + }, + addIssues: { + value: (issues2) => inst.issues.push(...issues2) + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + } + // enumerable: false, + } + }); +}; +var ZodError2 = $constructor("ZodError", initializer2); +var ZodRealError = $constructor("ZodError", initializer2, { + Parent: Error +}); + +// node_modules/zod/v4/classic/parse.js +var parse2 = /* @__PURE__ */ _parse(ZodRealError); +var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); +var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError); +var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); + +// node_modules/zod/v4/classic/schemas.js +var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + $ZodType.init(inst, def); + inst.def = def; + Object.defineProperty(inst, "_def", { value: def }); + inst.check = (...checks) => { + return inst.clone( + { + ...def, + checks: [ + ...def.checks ?? [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + } + // { parent: true } + ); + }; + inst.clone = (def2, params) => clone(inst, def2, params); + inst.brand = () => inst; + inst.register = (reg, meta) => { + reg.add(inst, meta); + return inst; + }; + inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse3(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.refine = (check2, params) => inst.check(refine(check2, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(_overwrite(fn)); + inst.optional = () => optional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg) => union([inst, arg]); + inst.and = (arg) => intersection(inst, arg); + inst.transform = (tx) => pipe(inst, transform(tx)); + inst.default = (def2) => _default(inst, def2); + inst.prefault = (def2) => prefault(inst, def2); + inst.catch = (params) => _catch(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + inst.describe = (description) => { + const cl = inst.clone(); + globalRegistry.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + inst.meta = (...args) => { + if (args.length === 0) { + return globalRegistry.get(inst); + } + const cl = inst.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }; + inst.isOptional = () => inst.safeParse(void 0).success; + inst.isNullable = () => inst.safeParse(null).success; + return inst; +}); +var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType2.init(inst, def); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + inst.regex = (...args) => inst.check(_regex(...args)); + inst.includes = (...args) => inst.check(_includes(...args)); + inst.startsWith = (...args) => inst.check(_startsWith(...args)); + inst.endsWith = (...args) => inst.check(_endsWith(...args)); + inst.min = (...args) => inst.check(_minLength(...args)); + inst.max = (...args) => inst.check(_maxLength(...args)); + inst.length = (...args) => inst.check(_length(...args)); + inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); + inst.lowercase = (params) => inst.check(_lowercase(params)); + inst.uppercase = (params) => inst.check(_uppercase(params)); + inst.trim = () => inst.check(_trim()); + inst.normalize = (...args) => inst.check(_normalize(...args)); + inst.toLowerCase = () => inst.check(_toLowerCase()); + inst.toUpperCase = () => inst.check(_toUpperCase()); +}); +var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params) => inst.check(_email(ZodEmail, params)); + inst.url = (params) => inst.check(_url(ZodURL, params)); + inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(_xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(_e164(ZodE164, params)); + inst.datetime = (params) => inst.check(datetime2(params)); + inst.date = (params) => inst.check(date2(params)); + inst.time = (params) => inst.check(time2(params)); + inst.duration = (params) => inst.check(duration2(params)); +}); +function string2(params) { + return _string(ZodString2, params); +} +var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType2.init(inst, def); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.int = (params) => inst.check(int(params)); + inst.safe = (params) => inst.check(int(params)); + inst.positive = (params) => inst.check(_gt(0, params)); + inst.nonnegative = (params) => inst.check(_gte(0, params)); + inst.negative = (params) => inst.check(_lt(0, params)); + inst.nonpositive = (params) => inst.check(_lte(0, params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + inst.step = (value, params) => inst.check(_multipleOf(value, params)); + inst.finite = () => inst; + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}); +function number2(params) { + return _number(ZodNumber2, params); +} +var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber2.init(inst, def); +}); +function int(params) { + return _int(ZodNumberFormat, params); +} +var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType2.init(inst, def); +}); +function boolean2(params) { + return _boolean(ZodBoolean2, params); +} +var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType2.init(inst, def); +}); +function _null3(params) { + return _null2(ZodNull2, params); +} +var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType2.init(inst, def); +}); +function unknown() { + return _unknown(ZodUnknown2); +} +var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType2.init(inst, def); +}); +function never(params) { + return _never(ZodNever2, params); +} +var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + ZodType2.init(inst, def); + inst.element = def.element; + inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); + inst.nonempty = (params) => inst.check(_minLength(1, params)); + inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(_length(len, params)); + inst.unwrap = () => inst.element; +}); +function array(element, params) { + return _array(ZodArray2, element, params); +} +var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + $ZodObject.init(inst, def); + ZodType2.init(inst, def); + util_exports.defineLazy(inst, "shape", () => def.shape); + inst.keyof = () => _enum(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); + inst.extend = (incoming) => { + return util_exports.extend(inst, incoming); + }; + inst.merge = (other) => util_exports.merge(inst, other); + inst.pick = (mask) => util_exports.pick(inst, mask); + inst.omit = (mask) => util_exports.omit(inst, mask); + inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]); + inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); +}); +function object2(shape, params) { + const def = { + type: "object", + get shape() { + util_exports.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + ...util_exports.normalizeParams(params) + }; + return new ZodObject2(def); +} +function looseObject(shape, params) { + return new ZodObject2({ + type: "object", + get shape() { + util_exports.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: unknown(), + ...util_exports.normalizeParams(params) + }); +} +var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType2.init(inst, def); + inst.options = def.options; +}); +function union(options, params) { + return new ZodUnion2({ + type: "union", + options, + ...util_exports.normalizeParams(params) + }); +} +var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion2.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion2({ + type: "union", + options, + discriminator, + ...util_exports.normalizeParams(params) + }); +} +var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType2.init(inst, def); +}); +function intersection(left, right) { + return new ZodIntersection2({ + type: "intersection", + left, + right + }); +} +var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + ZodType2.init(inst, def); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function record(keyType, valueType, params) { + return new ZodRecord2({ + type: "record", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); +} +var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType2.init(inst, def); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum2({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum2({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; +}); +function _enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum2({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); +} +var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType2.init(inst, def); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + } + }); +}); +function literal(value, params) { + return new ZodLiteral2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util_exports.normalizeParams(params) + }); +} +var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + ZodType2.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + _issue.continue ?? (_issue.continue = true); + payload.issues.push(util_exports.issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output2) => { + payload.value = output2; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); +} +var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; +}); +function optional(innerType) { + return new ZodOptional2({ + type: "optional", + innerType + }); +} +var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable2({ + type: "nullable", + innerType + }); +} +var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function _default(innerType, defaultValue) { + return new ZodDefault2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; + } + }); +} +var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; + } + }); +} +var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...util_exports.normalizeParams(params) + }); +} +var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType2.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function _catch(innerType, catchValue) { + return new ZodCatch2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); +} +var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType2.init(inst, def); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + // ...util.normalizeParams(params), + }); +} +var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType2.init(inst, def); +}); +function readonly(innerType) { + return new ZodReadonly2({ + type: "readonly", + innerType + }); +} +var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType2.init(inst, def); +}); +function check(fn) { + const ch = new $ZodCheck({ + check: "custom" + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom2(fn, _params) { + return _custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +function superRefine(fn) { + const ch = check((payload) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(util_exports.issue(_issue)); + } + }; + return fn(payload.value, payload); + }); + return ch; +} +function preprocess(fn, schema) { + return pipe(transform(fn), schema); +} + +// node_modules/zod/v4/classic/external.js +config(en_default2()); + +// node_modules/@modelcontextprotocol/sdk/dist/esm/types.js +var LATEST_PROTOCOL_VERSION = "2025-11-25"; +var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"]; +var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +var JSONRPC_VERSION = "2.0"; +var AssertObjectSchema = custom2((v) => v !== null && (typeof v === "object" || typeof v === "function")); +var ProgressTokenSchema = union([string2(), number2().int()]); +var CursorSchema = string2(); +var TaskCreationParamsSchema = looseObject({ + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl: number2().optional(), + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: number2().optional() +}); +var TaskMetadataSchema = object2({ + ttl: number2().optional() +}); +var RelatedTaskMetadataSchema = object2({ + taskId: string2() +}); +var RequestMetaSchema = looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +var BaseRequestParamsSchema = object2({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); +var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: TaskMetadataSchema.optional() +}); +var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +var RequestSchema = object2({ + method: string2(), + params: BaseRequestParamsSchema.loose().optional() +}); +var NotificationsParamsSchema = object2({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +var NotificationSchema = object2({ + method: string2(), + params: NotificationsParamsSchema.loose().optional() +}); +var ResultSchema = looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() +}); +var RequestIdSchema = union([string2(), number2().int()]); +var JSONRPCRequestSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +var JSONRPCNotificationSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +var JSONRPCResultResponseSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +var ErrorCode; +(function(ErrorCode2) { + ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; + ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout"; + ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError"; + ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; + ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; +})(ErrorCode || (ErrorCode = {})); +var JSONRPCErrorResponseSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: object2({ + /** + * The error type that occurred. + */ + code: number2().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string2(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: unknown().optional() + }) +}).strict(); +var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +var JSONRPCMessageSchema = union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +var EmptyResultSchema = ResultSchema.strict(); +var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: string2().optional() +}); +var CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +var IconSchema = object2({ + /** + * URL or data URI for the icon. + */ + src: string2(), + /** + * Optional MIME type for the icon. + */ + mimeType: string2().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: array(string2()).optional(), + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme: _enum(["light", "dark"]).optional() +}); +var IconsSchema = object2({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons: array(IconSchema).optional() +}); +var BaseMetadataSchema = object2({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: string2(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: string2().optional() +}); +var ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: string2(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: string2().optional(), + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description: string2().optional() +}); +var FormElicitationCapabilitySchema = intersection(object2({ + applyDefaults: boolean2().optional() +}), record(string2(), unknown())); +var ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value)) { + if (Object.keys(value).length === 0) { + return { form: {} }; + } + } + return value; +}, intersection(object2({ + form: FormElicitationCapabilitySchema.optional(), + url: AssertObjectSchema.optional() +}), record(string2(), unknown()).optional())); +var ClientTasksCapabilitySchema = looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for sampling requests. + */ + sampling: looseObject({ + createMessage: AssertObjectSchema.optional() + }).optional(), + /** + * Task support for elicitation requests. + */ + elicitation: looseObject({ + create: AssertObjectSchema.optional() + }).optional() + }).optional() +}); +var ServerTasksCapabilitySchema = looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for tool requests. + */ + tools: looseObject({ + call: AssertObjectSchema.optional() + }).optional() + }).optional() +}); +var ClientCapabilitiesSchema = object2({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: record(string2(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: object2({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }).optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: object2({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the client supports task creation. + */ + tasks: ClientTasksCapabilitySchema.optional(), + /** + * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: record(string2(), AssertObjectSchema).optional() +}); +var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string2(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +var InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +var ServerCapabilitiesSchema = object2({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: record(string2(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: object2({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server offers any resources to read. + */ + resources: object2({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: boolean2().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server offers any tools to call. + */ + tools: object2({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server supports task creation. + */ + tasks: ServerTasksCapabilitySchema.optional(), + /** + * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: record(string2(), AssertObjectSchema).optional() +}); +var InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string2(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: string2().optional() +}); +var InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +var PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +var ProgressSchema = object2({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: number2(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: optional(number2()), + /** + * An optional message describing the current progress. + */ + message: optional(string2()) +}); +var ProgressNotificationParamsSchema = object2({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema +}); +var ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: CursorSchema.optional() +}); +var PaginatedRequestSchema = RequestSchema.extend({ + params: PaginatedRequestParamsSchema.optional() +}); +var PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: CursorSchema.optional() +}); +var TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]); +var TaskSchema = object2({ + taskId: string2(), + status: TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: union([number2(), _null3()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string2(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string2(), + pollInterval: optional(number2()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: optional(string2()) +}); +var CreateTaskResultSchema = ResultSchema.extend({ + task: TaskSchema +}); +var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +var TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +var GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) +}); +var GetTaskResultSchema = ResultSchema.merge(TaskSchema); +var GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) +}); +var GetTaskPayloadResultSchema = ResultSchema.loose(); +var ListTasksRequestSchema = PaginatedRequestSchema.extend({ + method: literal("tasks/list") +}); +var ListTasksResultSchema = PaginatedResultSchema.extend({ + tasks: array(TaskSchema) +}); +var CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) +}); +var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +var ResourceContentsSchema = object2({ + /** + * The URI of this resource. + */ + uri: string2(), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string2()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var TextResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string2() +}); +var Base64Schema = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +var BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema +}); +var RoleSchema = _enum(["user", "assistant"]); +var AnnotationsSchema = object2({ + /** + * Intended audience(s) for the resource. + */ + audience: array(RoleSchema).optional(), + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: number2().min(0).max(1).optional(), + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: iso_exports.datetime({ offset: true }).optional() +}); +var ResourceSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: string2(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string2()), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string2()), + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size: optional(number2()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +var ResourceTemplateSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: string2(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string2()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: optional(string2()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: literal("resources/list") +}); +var ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: array(ResourceSchema) +}); +var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ + method: literal("resources/templates/list") +}); +var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: array(ResourceTemplateSchema) +}); +var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string2() +}); +var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +var ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +var ReadResourceResultSchema = ResultSchema.extend({ + contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) +}); +var ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +var SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +var UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: string2() +}); +var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +var PromptArgumentSchema = object2({ + /** + * The name of the argument. + */ + name: string2(), + /** + * A human-readable description of the argument. + */ + description: optional(string2()), + /** + * Whether this argument must be provided. + */ + required: optional(boolean2()) +}); +var PromptSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: optional(string2()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: optional(array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) +}); +var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: literal("prompts/list") +}); +var ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: array(PromptSchema) +}); +var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: string2(), + /** + * Arguments to use for templating the prompt. + */ + arguments: record(string2(), string2()).optional() +}); +var GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +var TextContentSchema = object2({ + type: literal("text"), + /** + * The text content of the message. + */ + text: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ImageContentSchema = object2({ + type: literal("image"), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var AudioContentSchema = object2({ + type: literal("audio"), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ToolUseContentSchema = object2({ + type: literal("tool_use"), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: string2(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: string2(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: record(string2(), unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var EmbeddedResourceSchema = object2({ + type: literal("resource"), + resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ResourceLinkSchema = ResourceSchema.extend({ + type: literal("resource_link") +}); +var ContentBlockSchema = union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +var PromptMessageSchema = object2({ + role: RoleSchema, + content: ContentBlockSchema +}); +var GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: string2().optional(), + messages: array(PromptMessageSchema) +}); +var PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var ToolAnnotationsSchema = object2({ + /** + * A human-readable title for the tool. + */ + title: string2().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: boolean2().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: boolean2().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: boolean2().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: boolean2().optional() +}); +var ToolExecutionSchema = object2({ + /** + * Indicates the tool's preference for task-augmented execution. + * - "required": Clients MUST invoke the tool as a task + * - "optional": Clients MAY invoke the tool as a task or normal request + * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to "forbidden". + */ + taskSupport: _enum(["required", "optional", "forbidden"]).optional() +}); +var ToolSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: string2().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: object2({ + type: literal("object"), + properties: record(string2(), AssertObjectSchema).optional(), + required: array(string2()).optional() + }).catchall(unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: object2({ + type: literal("object"), + properties: record(string2(), AssertObjectSchema).optional(), + required: array(string2()).optional() + }).catchall(unknown()).optional(), + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: literal("tools/list") +}); +var ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: array(ToolSchema) +}); +var CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: array(ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: record(string2(), unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: boolean2().optional() +}); +var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ + toolResult: unknown() +})); +var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: string2(), + /** + * Arguments to pass to the tool. + */ + arguments: record(string2(), unknown()).optional() +}); +var CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +var ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var ListChangedOptionsBaseSchema = object2({ + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If false, the callback will be called with null items, allowing manual refresh. + * + * @default true + */ + autoRefresh: boolean2().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to 0 to disable debouncing. + * + * @default 300 + */ + debounceMs: number2().int().nonnegative().default(300) +}); +var LoggingLevelSchema = _enum(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); +var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: LoggingLevelSchema +}); +var SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: string2().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown() +}); +var LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +var ModelHintSchema = object2({ + /** + * A hint for a model name. + */ + name: string2().optional() +}); +var ModelPreferencesSchema = object2({ + /** + * Optional hints to use for model selection. + */ + hints: array(ModelHintSchema).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: number2().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: number2().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: number2().min(0).max(1).optional() +}); +var ToolChoiceSchema = object2({ + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: _enum(["auto", "required", "none"]).optional() +}); +var ToolResultContentSchema = object2({ + type: literal("tool_result"), + toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + content: array(ContentBlockSchema).default([]), + structuredContent: object2({}).loose().optional(), + isError: boolean2().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); +var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +var SamplingMessageSchema = object2({ + role: RoleSchema, + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: string2().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: _enum(["none", "thisServer", "allServers"]).optional(), + temperature: number2().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: array(ToolSchema).optional(), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: ToolChoiceSchema.optional() +}); +var CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +var CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: string2(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens"]).or(string2())), + role: RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ + content: SamplingContentSchema +}); +var CreateMessageResultWithToolsSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: string2(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), + role: RoleSchema, + /** + * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + */ + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) +}); +var BooleanSchemaSchema = object2({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() +}); +var StringSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum(["email", "uri", "date", "date-time"]).optional(), + default: string2().optional() +}); +var NumberSchemaSchema = object2({ + type: _enum(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() +}); +var UntitledSingleSelectEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() +}); +var TitledSingleSelectEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object2({ + const: string2(), + title: string2() + })), + default: string2().optional() +}); +var LegacyTitledEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() +}); +var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +var UntitledMultiSelectEnumSchemaSchema = object2({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object2({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() +}); +var TitledMultiSelectEnumSchemaSchema = object2({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object2({ + anyOf: array(object2({ + const: string2(), + title: string2() + })) + }), + default: array(string2()).optional() +}); +var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); +var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); +var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing mode as "form". + */ + mode: literal("form").optional(), + /** + * The message to present to the user describing what information is being requested. + */ + message: string2(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: object2({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema), + required: array(string2()).optional() + }) +}); +var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: literal("url"), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string2(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string2(), + /** + * The URL that the user should navigate to. + */ + url: string2().url() +}); +var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +var ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: string2() +}); +var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +var ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: _enum(["accept", "decline", "cancel"]), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize null to undefined for leniency while maintaining type compatibility. + */ + content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) +}); +var ResourceTemplateReferenceSchema = object2({ + type: literal("ref/resource"), + /** + * The URI or URI template of the resource. + */ + uri: string2() +}); +var PromptReferenceSchema = object2({ + type: literal("ref/prompt"), + /** + * The name of the prompt or prompt template + */ + name: string2() +}); +var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: object2({ + /** + * The name of the argument + */ + name: string2(), + /** + * The value of the argument to use for completion matching. + */ + value: string2() + }), + context: object2({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: record(string2(), string2()).optional() + }).optional() +}); +var CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +var CompleteResultSchema = ResultSchema.extend({ + completion: looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: array(string2()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: optional(number2().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: optional(boolean2()) + }) +}); +var RootSchema = object2({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: string2().startsWith("file://"), + /** + * An optional name for the root. + */ + name: string2().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() +}); +var ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +var ListRootsResultSchema = ResultSchema.extend({ + roots: array(RootSchema) +}); +var RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +var ClientRequestSchema = union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +var ClientNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, + TaskStatusNotificationSchema +]); +var ClientResultSchema = union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +var ServerRequestSchema = union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema +]); +var ServerNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + TaskStatusNotificationSchema, + ElicitationCompleteNotificationSchema +]); +var ServerResultSchema = union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema +]); +var McpError = class _McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = "McpError"; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } + } + return new _McpError(code, message, data); + } +}; +var UrlElicitationRequiredError = class extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations + }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js +function isTerminal(status) { + return status === "completed" || status === "failed" || status === "cancelled"; +} + +// node_modules/zod-to-json-schema/dist/esm/Options.js +var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); + +// node_modules/zod-to-json-schema/dist/esm/parsers/string.js +var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); + +// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js +function getMethodLiteral(schema) { + const shape = getObjectShape(schema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error("Schema is missing a method literal"); + } + const value = getLiteralValue(methodSchema); + if (typeof value !== "string") { + throw new Error("Schema method literal must be a string"); + } + return value; +} +function parseWithCompat(schema, data) { + const result = safeParse2(schema, data); + if (!result.success) { + throw result.error; + } + return result.data; +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js +var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +var Protocol = class { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = /* @__PURE__ */ new Map(); + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + this._notificationHandlers = /* @__PURE__ */ new Map(); + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers = /* @__PURE__ */ new Map(); + this._timeoutInfo = /* @__PURE__ */ new Map(); + this._pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + this._taskProgressTokens = /* @__PURE__ */ new Map(); + this._requestResolvers = /* @__PURE__ */ new Map(); + this.setNotificationHandler(CancelledNotificationSchema, (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler(ProgressNotificationSchema, (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler( + PingRequestSchema, + // Automatic pong by default. + (_request) => ({}) + ); + this._taskStore = _options?.taskStore; + this._taskMessageQueue = _options?.taskMessageQueue; + if (this._taskStore) { + this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + } + return { + ...task + }; + }); + this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { + const handleTaskResult = async () => { + const taskId = request.params.taskId; + if (!await this._taskStore.getTask(taskId, extra.sessionId)) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + if (this._taskMessageQueue) { + let queuedMessage; + while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) { + if (queuedMessage.type === "response" || queuedMessage.type === "error") { + const message = queuedMessage.message; + const requestId = message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + this._requestResolvers.delete(requestId); + if (queuedMessage.type === "response") { + resolver(message); + } else { + const errorMessage2 = message; + const error2 = new McpError(errorMessage2.error.code, errorMessage2.error.message, errorMessage2.error.data); + resolver(error2); + } + } else { + const messageType = queuedMessage.type === "response" ? "Response" : "Error"; + this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); + } + continue; + } + await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); + } + } + const task = await this._taskStore.getTask(taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + if (!isTerminal(task.status)) { + await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId); + return await handleTaskResult(); + } + if (isTerminal(task.status)) { + const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); + this._clearTaskQueue(taskId, extra.sessionId); + return { + ...result, + _meta: { + ...result._meta, + [RELATED_TASK_META_KEY]: { + taskId + } + } + }; + } + return await handleTaskResult(); + }; + return await handleTaskResult(); + }); + this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { + try { + const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); + return { + tasks, + nextCursor, + _meta: {} + }; + } catch (error2) { + throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + }); + this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { + try { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); + } + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); + } + await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId); + this._clearTaskQueue(request.params.taskId, extra.sessionId); + const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!cancelledTask) { + throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); + } + return { + _meta: {}, + ...cancelledTask + }; + } catch (error2) { + if (error2 instanceof McpError) { + throw error2; + } + throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + }); + } + } + async _oncancel(notification) { + if (!notification.params.requestId) { + return; + } + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport2) { + if (this._transport) { + throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection."); + } + this._transport = transport2; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + _onclose?.(); + this._onclose(); + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error2) => { + _onerror?.(error2); + this._onerror(error2); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._onresponse(message); + } else if (isJSONRPCRequest(message)) { + this._onrequest(message, extra); + } else if (isJSONRPCNotification(message)) { + this._onnotification(message); + } else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); + } + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._taskProgressTokens.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) { + clearTimeout(info.timeoutId); + } + this._timeoutInfo.clear(); + for (const controller of this._requestHandlerAbortControllers.values()) { + controller.abort(); + } + this._requestHandlerAbortControllers.clear(); + const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + this.onclose?.(); + for (const handler of responseHandlers.values()) { + handler(error2); + } + } + _onerror(error2) { + this.onerror?.(error2); + } + _onnotification(notification) { + const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; + if (handler === void 0) { + return; + } + Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`))); + } + _onrequest(request, extra) { + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + const capturedTransport = this._transport; + const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; + const sessionId = capturedTransport?.sessionId; + const store = this._taskStore; + let relatedTaskFound = true; + let relatedTaskLookup; + if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) { + relatedTaskFound = false; + relatedTaskLookup = (async () => { + if (!await store.getTask(relatedTaskId, sessionId)) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`); + } + relatedTaskFound = true; + })(); + } + if (handler === void 0) { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: ErrorCode.MethodNotFound, + message: "Method not found" + } + }; + if (relatedTaskId && relatedTaskLookup) { + const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() }; + relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`))); + } else if (relatedTaskId && this._taskMessageQueue) { + this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`))); + } else { + capturedTransport?.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`))); + } + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0; + const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0; + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport?.sessionId, + _meta: request.params?._meta, + sendNotification: async (notification) => { + if (abortController.signal.aborted) + return; + const notificationOptions = { relatedRequestId: request.id }; + if (relatedTaskId) { + notificationOptions.relatedTask = { taskId: relatedTaskId }; + } + await this.notification(notification, notificationOptions); + }, + sendRequest: async (r, resultSchema, options) => { + if (abortController.signal.aborted) { + throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); + } + const requestOptions = { ...options, relatedRequestId: request.id }; + if (relatedTaskId && !requestOptions.relatedTask) { + requestOptions.relatedTask = { taskId: relatedTaskId }; + } + const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; + if (effectiveTaskId && taskStore) { + await taskStore.updateTaskStatus(effectiveTaskId, "input_required"); + } + return await this.request(r, resultSchema, requestOptions); + }, + authInfo: extra?.authInfo, + requestId: request.id, + requestInfo: extra?.requestInfo, + taskId: relatedTaskId, + taskStore, + taskRequestedTtl: taskCreationParams?.ttl, + closeSSEStream: extra?.closeSSEStream, + closeStandaloneSSEStream: extra?.closeStandaloneSSEStream + }; + (relatedTaskLookup ?? Promise.resolve()).then(() => { + if (relatedTaskLookup && abortController.signal.aborted) { + throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); + } + if (taskCreationParams) { + this.assertTaskHandlerCapability(request.method); + } + }).then(() => handler(request, fullExtra)).then(async (result) => { + if (abortController.signal.aborted) { + return; + } + const response = { + result, + jsonrpc: "2.0", + id: request.id + }; + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: "response", + message: response, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } else { + await capturedTransport?.send(response); + } + }, async (error2) => { + if (abortController.signal.aborted) { + return; + } + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError, + message: error2.message ?? "Internal error", + ...error2["data"] !== void 0 && { data: error2["data"] } + } + }; + if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) { + await this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } else { + await capturedTransport?.send(errorResponse); + } + }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) { + this._requestHandlerAbortControllers.delete(request.id); + } + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } catch (error2) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error2); + return; + } + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + const resolver = this._requestResolvers.get(messageId); + if (resolver) { + this._requestResolvers.delete(messageId); + if (isJSONRPCResultResponse(response)) { + resolver(response); + } else { + const error2 = new McpError(response.error.code, response.error.message, response.error.data); + resolver(error2); + } + return; + } + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + let isTaskResponse = false; + if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") { + const result = response.result; + if (result.task && typeof result.task === "object") { + const task = result.task; + if (typeof task.taskId === "string") { + isTaskResponse = true; + this._taskProgressTokens.set(task.taskId, messageId); + } + } + } + if (!isTaskResponse) { + this._progressHandlers.delete(messageId); + } + if (isJSONRPCResultResponse(response)) { + handler(response); + } else { + const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error2); + } + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + async *requestStream(request, resultSchema, options) { + const { task } = options ?? {}; + if (!task) { + try { + const result = await this.request(request, resultSchema, options); + yield { type: "result", result }; + } catch (error2) { + yield { + type: "error", + error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2)) + }; + } + return; + } + let taskId; + try { + const createResult = await this.request(request, CreateTaskResultSchema, options); + if (createResult.task) { + taskId = createResult.task.taskId; + yield { type: "taskCreated", task: createResult.task }; + } else { + throw new McpError(ErrorCode.InternalError, "Task creation did not return a task"); + } + while (true) { + const task2 = await this.getTask({ taskId }, options); + yield { type: "taskStatus", task: task2 }; + if (isTerminal(task2.status)) { + if (task2.status === "completed") { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: "result", result }; + } else if (task2.status === "failed") { + yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) + }; + } else if (task2.status === "cancelled") { + yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) + }; + } + return; + } + if (task2.status === "input_required") { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: "result", result }; + return; + } + const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3; + await new Promise((resolve) => setTimeout(resolve, pollInterval)); + options?.signal?.throwIfAborted(); + } + } catch (error2) { + yield { + type: "error", + error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2)) + }; + } + } + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; + return new Promise((resolve, reject) => { + const earlyReject = (error2) => { + reject(error2); + }; + if (!this._transport) { + earlyReject(new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) { + try { + this.assertCapabilityForMethod(request.method); + if (task) { + this.assertTaskCapability(request.method); + } + } catch (e) { + earlyReject(e); + return; + } + } + options?.signal?.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta || {}, + progressToken: messageId + } + }; + } + if (task) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + task + }; + } + if (relatedTask) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + _meta: { + ...jsonrpcRequest.params?._meta || {}, + [RELATED_TASK_META_KEY]: relatedTask + } + }; + } + const cancel = (reason) => { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._transport?.send({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`))); + const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); + reject(error2); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = safeParse2(resultSchema, response.result); + if (!parseResult.success) { + reject(parseResult.error); + } else { + resolve(parseResult.data); + } + } catch (error2) { + reject(error2); + } + }); + options?.signal?.addEventListener("abort", () => { + cancel(options?.signal?.reason); + }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + const relatedTaskId = relatedTask?.taskId; + if (relatedTaskId) { + const responseResolver = (response) => { + const handler = this._responseHandlers.get(messageId); + if (handler) { + handler(response); + } else { + this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); + } + }; + this._requestResolvers.set(messageId, responseResolver); + this._enqueueTaskMessage(relatedTaskId, { + type: "request", + message: jsonrpcRequest, + timestamp: Date.now() + }).catch((error2) => { + this._cleanupTimeout(messageId); + reject(error2); + }); + } else { + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => { + this._cleanupTimeout(messageId); + reject(error2); + }); + } + }); + } + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + async getTask(params, options) { + return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options); + } + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + async getTaskResult(params, resultSchema, options) { + return this.request({ method: "tasks/result", params }, resultSchema, options); + } + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + async listTasks(params, options) { + return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options); + } + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + async cancelTask(params, options) { + return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + if (!this._transport) { + throw new Error("Not connected"); + } + this.assertNotificationCapability(notification.method); + const relatedTaskId = options?.relatedTask?.taskId; + if (relatedTaskId) { + const jsonrpcNotification2 = { + ...notification, + jsonrpc: "2.0", + params: { + ...notification.params, + _meta: { + ...notification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._enqueueTaskMessage(relatedTaskId, { + type: "notification", + message: jsonrpcNotification2, + timestamp: Date.now() + }); + return; + } + const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; + if (canDebounce) { + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) { + return; + } + let jsonrpcNotification2 = { + ...notification, + jsonrpc: "2.0" + }; + if (options?.relatedTask) { + jsonrpcNotification2 = { + ...jsonrpcNotification2, + params: { + ...jsonrpcNotification2.params, + _meta: { + ...jsonrpcNotification2.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + this._transport?.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2)); + }); + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: "2.0" + }; + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...jsonrpcNotification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = getMethodLiteral(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = parseWithCompat(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = getMethodLiteral(notificationSchema); + this._notificationHandlers.set(method, (notification) => { + const parsed = parseWithCompat(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + _cleanupTaskProgressHandler(taskId) { + const progressToken = this._taskProgressTokens.get(taskId); + if (progressToken !== void 0) { + this._progressHandlers.delete(progressToken); + this._taskProgressTokens.delete(taskId); + } + } + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + async _enqueueTaskMessage(taskId, message, sessionId) { + if (!this._taskStore || !this._taskMessageQueue) { + throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured"); + } + const maxQueueSize = this._options?.maxTaskQueueSize; + await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize); + } + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + async _clearTaskQueue(taskId, sessionId) { + if (this._taskMessageQueue) { + const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); + for (const message of messages) { + if (message.type === "request" && isJSONRPCRequest(message.message)) { + const requestId = message.message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed")); + this._requestResolvers.delete(requestId); + } else { + this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); + } + } + } + } + } + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @param sessionId Session of the request that waits, passed to the task store + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + async _waitForTaskUpdate(taskId, signal, sessionId) { + let interval = this._options?.defaultTaskPollInterval ?? 1e3; + try { + const task = await this._taskStore?.getTask(taskId, sessionId); + if (task?.pollInterval) { + interval = task.pollInterval; + } + } catch { + } + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + return; + } + const timeoutId = setTimeout(resolve, interval); + signal.addEventListener("abort", () => { + clearTimeout(timeoutId); + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + }, { once: true }); + }); + } + requestTaskStore(request, sessionId) { + const taskStore = this._taskStore; + if (!taskStore) { + throw new Error("No task store configured"); + } + return { + createTask: async (taskParams) => { + if (!request) { + throw new Error("No request provided"); + } + return await taskStore.createTask(taskParams, request.id, { + method: request.method, + params: request.params + }, sessionId); + }, + getTask: async (taskId) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + } + return task; + }, + storeTaskResult: async (taskId, status, result) => { + await taskStore.storeTaskResult(taskId, status, result, sessionId); + const task = await taskStore.getTask(taskId, sessionId); + if (task) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: task + }); + await this.notification(notification); + if (isTerminal(task.status)) { + this._cleanupTaskProgressHandler(taskId); + } + } + }, + getTaskResult: (taskId) => { + return taskStore.getTaskResult(taskId, sessionId); + }, + updateTaskStatus: async (taskId, status, statusMessage) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); + } + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); + const updatedTask = await taskStore.getTask(taskId, sessionId); + if (updatedTask) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: updatedTask + }); + await this.notification(notification); + if (isTerminal(updatedTask.status)) { + this._cleanupTaskProgressHandler(taskId); + } + } + }, + listTasks: (cursor) => { + return taskStore.listTasks(cursor, sessionId); + } + }; + } +}; +function isPlainObject2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) + continue; + const baseValue = result[k]; + if (isPlainObject2(baseValue) && isPlainObject2(addValue)) { + result[k] = { ...baseValue, ...addValue }; + } else { + result[k] = addValue; + } + } + return result; +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js +var import_ajv = __toESM(require_ajv(), 1); +var import_ajv_formats = __toESM(require_dist(), 1); +function createDefaultAjvInstance() { + const ajv = new import_ajv.default({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + const addFormats = import_ajv_formats.default; + addFormats(ajv); + return ajv; +} +var AjvJsonSchemaValidator = class { + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv) { + this._ajv = ajv ?? createDefaultAjvInstance(); + } + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema) : this._ajv.compile(schema); + return (input) => { + const valid = ajvValidator(input); + if (valid) { + return { + valid: true, + data: input, + errorMessage: void 0 + }; + } else { + return { + valid: false, + data: void 0, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + } + }; + } +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js +var ExperimentalServerTasks = class { + constructor(_server) { + this._server = _server; + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * This method provides streaming access to request processing, allowing you to + * observe intermediate task status updates for task-augmented requests. + * + * @param request - The request to send + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + requestStream(request, resultSchema, options) { + return this._server.requestStream(request, resultSchema, options); + } + /** + * Sends a sampling request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages + * before the final result. + * + * @example + * ```typescript + * const stream = server.experimental.tasks.createMessageStream({ + * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }], + * maxTokens: 100 + * }, { + * onprogress: (progress) => { + * // Handle streaming tokens via progress notifications + * console.log('Progress:', progress.message); + * } + * }); + * + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - The sampling request parameters + * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + createMessageStream(params, options) { + const clientCapabilities = this._server.getClientCapabilities(); + if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) { + throw new Error("Client does not support sampling tools capability."); + } + if (params.messages.length > 0) { + const lastMessage = params.messages[params.messages.length - 1]; + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) { + throw new Error("The last message must contain only tool_result content if any is present"); + } + if (!hasPreviousToolUse) { + throw new Error("tool_result blocks are not matching any tool_use from the previous message"); + } + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { + throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + } + return this.requestStream({ + method: "sampling/createMessage", + params + }, CreateMessageResultSchema, options); + } + /** + * Sends an elicitation request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated' + * and 'taskStatus' messages before the final result. + * + * @example + * ```typescript + * const stream = server.experimental.tasks.elicitInputStream({ + * mode: 'url', + * message: 'Please authenticate', + * elicitationId: 'auth-123', + * url: 'https://example.com/auth' + * }, { + * task: { ttl: 300000 } // Task-augmented for long-running auth flow + * }); + * + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('User action:', message.result.action); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @param params - The elicitation request parameters + * @param options - Optional request options (timeout, signal, task creation params, etc.) + * @returns AsyncGenerator that yields ResponseMessage objects + * + * @experimental + */ + elicitInputStream(params, options) { + const clientCapabilities = this._server.getClientCapabilities(); + const mode = params.mode ?? "form"; + switch (mode) { + case "url": { + if (!clientCapabilities?.elicitation?.url) { + throw new Error("Client does not support url elicitation."); + } + break; + } + case "form": { + if (!clientCapabilities?.elicitation?.form) { + throw new Error("Client does not support form elicitation."); + } + break; + } + } + const normalizedParams = mode === "form" && params.mode === void 0 ? { ...params, mode: "form" } : params; + return this.requestStream({ + method: "elicitation/create", + params: normalizedParams + }, ElicitResultSchema, options); + } + /** + * Gets the current status of a task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * @returns The task status + * + * @experimental + */ + async getTask(taskId, options) { + return this._server.getTask({ taskId }, options); + } + /** + * Retrieves the result of a completed task. + * + * @param taskId - The task identifier + * @param resultSchema - Zod schema for validating the result + * @param options - Optional request options + * @returns The task result + * + * @experimental + */ + async getTaskResult(taskId, resultSchema, options) { + return this._server.getTaskResult({ taskId }, resultSchema, options); + } + /** + * Lists tasks with optional pagination. + * + * @param cursor - Optional pagination cursor + * @param options - Optional request options + * @returns List of tasks with optional next cursor + * + * @experimental + */ + async listTasks(cursor, options) { + return this._server.listTasks(cursor ? { cursor } : void 0, options); + } + /** + * Cancels a running task. + * + * @param taskId - The task identifier + * @param options - Optional request options + * + * @experimental + */ + async cancelTask(taskId, options) { + return this._server.cancelTask({ taskId }, options); + } +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js +function assertToolsCallTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case "tools/call": + if (!requests.tools?.call) { + throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`); + } + break; + default: + break; + } +} +function assertClientRequestTaskCapability(requests, method, entityName) { + if (!requests) { + throw new Error(`${entityName} does not support task creation (required for ${method})`); + } + switch (method) { + case "sampling/createMessage": + if (!requests.sampling?.createMessage) { + throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`); + } + break; + case "elicitation/create": + if (!requests.elicitation?.create) { + throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`); + } + break; + default: + break; + } +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js +var Server = class extends Protocol { + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._loggingLevels = /* @__PURE__ */ new Map(); + this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + this.isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + this._capabilities = options?.capabilities ?? {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request)); + this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); + if (this._capabilities.logging) { + this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { + const transportSessionId = extra.sessionId || extra.requestInfo?.headers["mcp-session-id"] || void 0; + const { level } = request.params; + const parseResult = LoggingLevelSchema.safeParse(level); + if (parseResult.success) { + this._loggingLevels.set(transportSessionId, parseResult.data); + } + return {}; + }); + } + } + /** + * Access experimental features. + * + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + get experimental() { + if (!this._experimental) { + this._experimental = { + tasks: new ExperimentalServerTasks(this) + }; + } + return this._experimental; + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error("Cannot register capabilities after connecting to transport"); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce server-side validation for tools/call. + */ + setRequestHandler(requestSchema, handler) { + const shape = getObjectShape(requestSchema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error("Schema is missing a method literal"); + } + const methodValue = getLiteralValue(methodSchema); + if (typeof methodValue !== "string") { + throw new Error("Schema method literal must be a string"); + } + const method = methodValue; + if (method === "tools/call") { + const wrappedHandler = async (request, extra) => { + const validatedRequest = safeParse2(CallToolRequestSchema, request); + if (!validatedRequest.success) { + const errorMessage2 = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage2}`); + } + const { params } = validatedRequest.data; + const result = await Promise.resolve(handler(request, extra)); + if (params.task) { + const taskValidationResult = safeParse2(CreateTaskResultSchema, result); + if (!taskValidationResult.success) { + const errorMessage2 = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage2}`); + } + return taskValidationResult.data; + } + const validationResult = safeParse2(CallToolResultSchema, result); + if (!validationResult.success) { + const errorMessage2 = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage2}`); + } + return validationResult.data; + }; + return super.setRequestHandler(requestSchema, wrappedHandler); + } + return super.setRequestHandler(requestSchema, handler); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) { + throw new Error(`Client does not support sampling (required for ${method})`); + } + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) { + throw new Error(`Client does not support elicitation (required for ${method})`); + } + break; + case "roots/list": + if (!this._clientCapabilities?.roots) { + throw new Error(`Client does not support listing roots (required for ${method})`); + } + break; + case "ping": + break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) { + throw new Error(`Server does not support notifying about resources (required for ${method})`); + } + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) { + throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); + } + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) { + throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); + } + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error(`Client does not support URL elicitation (required for ${method})`); + } + break; + case "notifications/cancelled": + break; + case "notifications/progress": + break; + } + } + assertRequestHandlerCapability(method) { + if (!this._capabilities) { + return; + } + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case "logging/setLevel": + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case "tasks/get": + case "tasks/list": + case "tasks/result": + case "tasks/cancel": + if (!this._capabilities.tasks) { + throw new Error(`Server does not support tasks capability (required for ${method})`); + } + break; + case "ping": + case "initialize": + break; + } + } + assertTaskCapability(method) { + assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, "Client"); + } + assertTaskHandlerCapability(method) { + if (!this._capabilities) { + return; + } + assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, "Server"); + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion() { + return this._clientVersion; + } + getCapabilities() { + return this._capabilities; + } + async ping() { + return this.request({ method: "ping" }, EmptyResultSchema); + } + // Implementation + async createMessage(params, options) { + if (params.tools || params.toolChoice) { + if (!this._clientCapabilities?.sampling?.tools) { + throw new Error("Client does not support sampling tools capability."); + } + } + if (params.messages.length > 0) { + const lastMessage = params.messages[params.messages.length - 1]; + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) { + throw new Error("The last message must contain only tool_result content if any is present"); + } + if (!hasPreviousToolUse) { + throw new Error("tool_result blocks are not matching any tool_use from the previous message"); + } + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) { + throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + } + if (params.tools) { + return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options); + } + return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options); + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + async elicitInput(params, options) { + const mode = params.mode ?? "form"; + switch (mode) { + case "url": { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error("Client does not support url elicitation."); + } + const urlParams = params; + return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options); + } + case "form": { + if (!this._clientCapabilities?.elicitation?.form) { + throw new Error("Client does not support form elicitation."); + } + const formParams = params.mode === "form" ? params : { ...params, mode: "form" }; + const result = await this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options); + if (result.action === "accept" && result.content && formParams.requestedSchema) { + try { + const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); + const validationResult = validator(result.content); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } + } catch (error2) { + if (error2 instanceof McpError) { + throw error2; + } + throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error2 instanceof Error ? error2.message : String(error2)}`); + } + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) { + throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)"); + } + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { + elicitationId + } + }, options); + } + async listRoots(params, options) { + return this.request({ method: "roots/list", params }, ListRootsResultSchema, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging) { + if (!this.isMessageIgnored(params.level, sessionId)) { + return this.notification({ method: "notifications/message", params }); + } + } + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + async sendResourceListChanged() { + return this.notification({ + method: "notifications/resources/list_changed" + }); + } + async sendToolListChanged() { + return this.notification({ method: "notifications/tools/list_changed" }); + } + async sendPromptListChanged() { + return this.notification({ method: "notifications/prompts/list_changed" }); + } +}; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js +import process2 from "node:process"; + +// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js +var STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; +var ReadBuffer = class { + constructor(options) { + this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; + } + append(chunk) { + const newSize = (this._buffer?.length ?? 0) + chunk.length; + if (newSize > this._maxBufferSize) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); + } + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) { + return null; + } + const index = this._buffer.indexOf("\n"); + if (index === -1) { + return null; + } + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +// node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js +var StdioServerTransport = class { + constructor(_stdin = process2.stdin, _stdout = process2.stdout, options) { + this._stdin = _stdin; + this._stdout = _stdout; + this._started = false; + this._ondata = (chunk) => { + try { + this._readBuffer.append(chunk); + this.processReadBuffer(); + } catch (error2) { + this.onerror?.(error2); + this.close().catch(() => { + }); + } + }; + this._onerror = (error2) => { + this.onerror?.(error2); + }; + this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); + } + /** + * Starts listening for messages on stdin. + */ + async start() { + if (this._started) { + throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + } + this._started = true; + this._stdin.on("data", this._ondata); + this._stdin.on("error", this._onerror); + } + processReadBuffer() { + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + this.onmessage?.(message); + } catch (error2) { + this.onerror?.(error2); + } + } + } + async close() { + this._stdin.off("data", this._ondata); + this._stdin.off("error", this._onerror); + const remainingDataListeners = this._stdin.listenerCount("data"); + if (remainingDataListeners === 0) { + this._stdin.pause(); + } + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + return new Promise((resolve) => { + const json = serializeMessage(message); + if (this._stdout.write(json)) { + resolve(); + } else { + this._stdout.once("drain", resolve); + } + }); + } +}; + +// src/shared.ts +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; + +// src/domain/errors.ts +var TeamError = class extends Error { + code; + constructor(code, message, options) { + super(message, options); + this.name = "TeamError"; + this.code = code; + } + toJSON() { + return serializeTeamError(this); + } +}; +function serializeTeamError(err) { + const out = { name: "TeamError", code: err.code, message: err.message }; + const seen = new WeakSet([err]); + const cause = err.cause; + if (cause !== void 0 && cause !== null) out.cause = serializeCause(cause, seen); + return out; +} +function serializeCause(cause, seen) { + if (!(cause instanceof Error)) return { message: String(cause) }; + if (seen.has(cause)) return { name: cause.name, message: "[circular cause]" }; + seen.add(cause); + if (cause instanceof TeamError) { + const serialized = { + name: "TeamError", + code: cause.code, + message: cause.message + }; + const inner2 = cause.cause; + if (inner2 !== void 0 && inner2 !== null) serialized.cause = serializeCause(inner2, seen); + return serialized; + } + const plain = { name: cause.name, message: cause.message }; + const inner = cause.cause; + if (inner !== void 0 && inner !== null) plain.cause = serializeCause(inner, seen); + return plain; +} +function isTeamError(x) { + return x instanceof TeamError; +} + +// src/domain/config.ts +var TEAM_LIMIT_KEYS = [ + "maxMembers", + "maxTasks", + "maxMessageBytes", + "disposalTimeoutMs" +]; +function validateTeamLimits(input) { + const out = {}; + for (const key of TEAM_LIMIT_KEYS) { + const raw = input[key]; + const n = coerceInteger(raw); + if (n === void 0 || !Number.isSafeInteger(n) || n < 1) { + throw new TeamError("TEAM_INVALID_CONFIG", `${key} must be a positive safe integer`, { + cause: { key, value: raw } + }); + } + out[key] = n; + } + return out; +} +function coerceInteger(raw) { + if (typeof raw === "number") return raw; + if (typeof raw === "string" && /^-?\d+$/.test(raw.trim())) return Number(raw.trim()); + return void 0; +} +var DEFAULT_LEAD_MODE = "auto"; +var LEGACY_LEAD_MODE_MAP = { + orchestrator: "auto", + collaborator: "auto" +}; +function normalizeLeadMode(raw) { + if (typeof raw !== "string") return void 0; + if (raw === "off" || raw === "auto" || raw === "always") return raw; + return LEGACY_LEAD_MODE_MAP[raw]; +} +function validateLeadMode(raw) { + return normalizeLeadMode(raw) ?? DEFAULT_LEAD_MODE; +} + +// src/shared.ts +function dataDir() { + const candidates = [ + process.env.TEAM_PLUGIN_DATA, + process.env.ZCODE_PLUGIN_DATA, + process.env.CLAUDE_PLUGIN_DATA + ]; + for (const c of candidates) if (c && c.trim()) return c; + return path.join(os.homedir(), ".zcode", "agent-team-dev-data"); +} +function ensurePrivateDir(p) { + fs.mkdirSync(p, { recursive: true, mode: 448 }); + try { + fs.chmodSync(p, 448); + } catch { + } + return p; +} +function runtimeConfigPath() { + return path.join(dataDir(), "meta", "runtime-config.json"); +} +function writeRuntimeConfig(input) { + const file = runtimeConfigPath(); + fs.mkdirSync(path.dirname(file), { recursive: true }); + const tmp = `${file}.tmp-${process.pid}`; + const doc = { + version: 2, + interrupt: input.interrupt, + leadMode: input.leadMode, + limits: input.limits, + updatedAt: ts() + }; + const fd = fs.openSync(tmp, "w", 384); + try { + fs.writeFileSync(fd, JSON.stringify(doc, null, 2)); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + fs.renameSync(tmp, file); +} +function appendJsonl(file, obj) { + fs.appendFileSync(file, JSON.stringify(obj) + "\n", { mode: 384 }); + chmodPrivateOnce(file); +} +function ts() { + return (/* @__PURE__ */ new Date()).toISOString(); +} +var SENSITIVE_ENV_KEY = /(?:^|_)(?:KEY|KEYS|APIKEY|TOKEN|TOKENS|SECRET|SECRETS|PASSWORD|PASSWORDS|PASSWD|PASSPHRASE|AUTH|AUTHORIZATION|COOKIE|CREDENTIAL|CREDENTIALS|PRIVATE|URL|URI|DSN|CONNECTION)(?:$|_)/i; +function isSensitiveEnvKey(key) { + return SENSITIVE_ENV_KEY.test(key); +} +function sanitizeToolName(name) { + return typeof name === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(name) ? name : "unknown-tool"; +} +function metaFilePath(dataRoot, toolName, now2 = Date.now()) { + const safe = sanitizeToolName(toolName); + if (safe === "unknown-tool") return null; + const metaDir = path.resolve(dataRoot, "meta"); + const target = path.resolve(metaDir, `${safe}-${now2}-${Math.random().toString(36).slice(2, 8)}.json`); + if (!target.startsWith(`${metaDir}${path.sep}`)) return null; + return target; +} +function redactToolArguments(args) { + const redactValue = (value, depth = 0) => { + if (depth > 6) return ""; + if (typeof value === "string") { + return value.length > 256 ? `${value.slice(0, 256)}\u2026(${value.length} chars)` : value; + } + if (Array.isArray(value)) return value.map((item) => redactValue(item, depth + 1)); + if (typeof value === "object" && value !== null) { + const out = {}; + for (const [key, child] of Object.entries(value)) { + if (isSensitiveEnvKey(key)) { + out[key] = ""; + continue; + } + if (key === "message" || key === "prompt" || key === "description" || key === "content") { + const length = typeof child === "string" ? child.length : Array.isArray(child) ? child.length : 0; + out[key] = { redacted: true, chars: length }; + continue; + } + out[key] = redactValue(child, depth + 1); + } + return out; + } + return value; + }; + return redactValue(args); +} +function cleanupStaleSpecs(dataRoot, maxAgeMs = 5 * 6e4) { + const teamsRoot = path.join(dataRoot, "teams"); + let removed = 0; + let teams; + try { + teams = fs.readdirSync(teamsRoot); + } catch { + return 0; + } + const now2 = Date.now(); + for (const team of teams) { + const membersRoot = path.join(teamsRoot, team, "members"); + let members; + try { + members = fs.readdirSync(membersRoot); + } catch { + continue; + } + for (const member of members) { + const runDir = path.join(membersRoot, member, "run"); + let files; + try { + files = fs.readdirSync(runDir); + } catch { + continue; + } + for (const file of files) { + if (!file.endsWith(".spec.json")) continue; + const full = path.join(runDir, file); + try { + if (now2 - fs.statSync(full).mtimeMs > maxAgeMs) { + fs.unlinkSync(full); + removed += 1; + } + } catch { + } + } + } + } + return removed; +} +function pruneMetaFiles(dataRoot, maxFiles = 500, maxAgeMs = 7 * 24 * 36e5) { + const dir = path.join(dataRoot, "meta"); + let entries; + try { + entries = fs.readdirSync(dir).filter((name) => name.endsWith(".json")).map((name) => { + const full = path.join(dir, name); + return { name, mtimeMs: fs.statSync(full).mtimeMs }; + }); + } catch { + return 0; + } + const now2 = Date.now(); + let removed = 0; + const stale = entries.filter((e) => now2 - e.mtimeMs > maxAgeMs); + const remaining = entries.filter((e) => now2 - e.mtimeMs <= maxAgeMs).sort((a, b) => a.mtimeMs - b.mtimeMs); + const excess = Math.max(0, remaining.length - maxFiles); + for (const entry of [...stale, ...remaining.slice(0, excess)]) { + try { + fs.unlinkSync(path.join(dir, entry.name)); + removed += 1; + } catch { + } + } + return removed; +} +var chmodded = /* @__PURE__ */ new Set(); +function chmodPrivateOnce(file) { + if (chmodded.has(file)) return; + chmodded.add(file); + try { + fs.chmodSync(file, 384); + } catch { + } +} +var LIMIT_KEYS = [ + ["maxMembers", "TEAM_MAX_MEMBERS", 8], + ["maxTasks", "TEAM_MAX_TASKS", 256], + ["maxMessageBytes", "TEAM_MAX_MESSAGE_BYTES", 65536], + ["disposalTimeoutMs", "TEAM_DISPOSAL_TIMEOUT_MS", 5e3] +]; +function loadConfig() { + const input = {}; + for (const [key, envName, def] of LIMIT_KEYS) { + const raw = process.env[envName]; + input[key] = raw === void 0 || raw === "" ? def : raw; + } + try { + return { ok: true, values: validateTeamLimits(input) }; + } catch (err) { + const detail = err instanceof Error ? err.message : String(err); + return { + ok: false, + error: `TEAM_INVALID_CONFIG: ${detail}\uFF08\u8BF7\u5728 Settings \u2192 Plugins \u2192 agent-team \u7684\u7528\u6237\u914D\u7F6E\u4E2D\u6539\u56DE\u6B63\u6574\u6570\uFF09\u3002` + }; + } +} +function logErr(scope, msg, extra) { + try { + process.stderr.write( + JSON.stringify({ ts: ts(), scope, msg, extra }) + "\n" + ); + } catch { + } +} + +// src/coord/lock.ts +import crypto2 from "node:crypto"; +import fs4 from "node:fs"; +import path4 from "node:path"; +import { spawnSync } from "node:child_process"; + +// src/coord/identity.ts +import { randomUUID } from "node:crypto"; +var cachedBootId; +function bootId() { + cachedBootId ??= randomUUID(); + return cachedBootId; +} +function writerId() { + return `${bootId()}:${process.pid}`; +} +function parseWriterId(writer) { + const parts = writer.split(":"); + if (parts.length === 3) { + const [boot2, rawPid2, token] = parts; + const pid2 = Number(rawPid2); + if (boot2.length > 0 && token.length > 0 && Number.isInteger(pid2)) return { bootId: boot2, pid: pid2, token }; + return void 0; + } + if (parts.length !== 2) return void 0; + const [boot, rawPid] = parts; + const pid = Number(rawPid); + if (boot.length === 0 || !Number.isInteger(pid)) return void 0; + return { bootId: boot, pid }; +} + +// src/provider/procgroup.ts +import { execFile } from "node:child_process"; +import fs3 from "node:fs"; +import path3 from "node:path"; +import { fileURLToPath } from "node:url"; + +// src/provider/member-files.ts +import fs2 from "node:fs"; +import path2 from "node:path"; +function teamEverCreated(teamDir, leadSessionId) { + let entries; + try { + entries = fs2.readdirSync(path2.join(teamDir, "members")); + } catch { + return false; + } + return entries.some((entry) => entry !== leadSessionId); +} +function memberPaths(teamDir, memberId) { + const memberDir = path2.join(teamDir, "members", memberId); + const runDir = path2.join(memberDir, "run"); + return { + memberDir, + originFile: path2.join(memberDir, "origin.json"), + receiptsFile: path2.join(memberDir, "receipts.jsonl"), + stopBudgetFile: path2.join(memberDir, "stop-budget.json"), + runDir, + currentFile: path2.join(runDir, "current.json"), + drainMarkerFile: path2.join(runDir, "drain-requested.json"), + modelFailedFile: path2.join(memberDir, "model-failed.json") + }; +} +function turnFile(runDir, turnId) { + return path2.join(runDir, `${turnId}.json`); +} +function writeJsonAtomic(file, value) { + fs2.mkdirSync(path2.dirname(file), { recursive: true, mode: 448 }); + const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const fd = fs2.openSync(tmp, "w", 384); + try { + fs2.writeFileSync(fd, JSON.stringify(value, null, 2)); + fs2.fsyncSync(fd); + } finally { + fs2.closeSync(fd); + } + fs2.renameSync(tmp, file); +} +function readJson(file) { + let raw; + try { + raw = fs2.readFileSync(file, "utf8"); + } catch (err) { + if (err.code === "ENOENT") return void 0; + throw err; + } + return JSON.parse(raw); +} +function writeOrigin(paths, origin) { + writeJsonAtomic(paths.originFile, origin); +} +function readOrigin(paths) { + return readJson(paths.originFile); +} +function writeTurn(runDir, turn) { + writeJsonAtomic(turnFile(runDir, turn.turnId), turn); +} +function readTurn(runDir, turnId) { + return readJson(turnFile(runDir, turnId)); +} +function setCurrentTurn(paths, turnId) { + writeJsonAtomic(paths.currentFile, { turnId }); +} +function readCurrentTurnId(paths) { + return readJson(paths.currentFile)?.turnId; +} +function listTurns(runDir) { + let names; + try { + names = fs2.readdirSync(runDir); + } catch (err) { + if (err.code === "ENOENT") return []; + throw err; + } + return names.filter((n) => /^turn-\d+\.json$/.test(n)).sort((a, b) => turnNumber(a) - turnNumber(b)).map((n) => readJson(path2.join(runDir, n))).filter((t) => t !== void 0); +} +function turnNumber(name) { + return Number(name.slice("turn-".length, -".json".length)); +} +function nextTurnId(runDir) { + let names = []; + try { + names = fs2.readdirSync(runDir); + } catch { + } + let max = 0; + for (const n of names) { + if (/^turn-\d+\.json$/.test(n)) max = Math.max(max, turnNumber(n)); + } + return `turn-${max + 1}`; +} +function appendReceipt(paths, receipt) { + fs2.mkdirSync(path2.dirname(paths.receiptsFile), { recursive: true, mode: 448 }); + const fd = fs2.openSync(paths.receiptsFile, "a", 384); + try { + fs2.writeFileSync(fd, JSON.stringify(receipt) + "\n"); + fs2.fsyncSync(fd); + } finally { + fs2.closeSync(fd); + } +} +function readReceipts(paths) { + let raw; + try { + raw = fs2.readFileSync(paths.receiptsFile, "utf8"); + } catch (err) { + if (err.code === "ENOENT") return []; + throw err; + } + const receipts = []; + for (const line of raw.split("\n")) { + if (line.trim().length === 0) continue; + receipts.push(JSON.parse(line)); + } + return receipts; +} +function receiptMessageIds(paths) { + return new Set(readReceipts(paths).map((r) => r.messageId)); +} +function readStopBudget(paths) { + return readJson(paths.stopBudgetFile); +} +function writeStopBudget(paths, budget) { + writeJsonAtomic(paths.stopBudgetFile, budget); +} +function readModelFailed(paths) { + return readJson(paths.modelFailedFile); +} +function writeModelFailed(paths, record2) { + writeJsonAtomic(paths.modelFailedFile, record2); +} +function clearModelFailed(paths) { + try { + fs2.unlinkSync(paths.modelFailedFile); + } catch { + } +} + +// src/provider/procgroup.ts +var HELPER_DEFAULT = path3.join(path3.dirname(fileURLToPath(import.meta.url)), "detach-helper.mjs"); +var SPAWN_HELPER_TIMEOUT_MS = 1e4; +async function spawnDetached(spec) { + const dir = path3.dirname(spec.stdoutFile); + const specFile = spec.specFile ?? path3.join(dir, `${path3.basename(spec.stdoutFile, ".out")}.spec.json`); + const resultFile = spec.resultFile ?? path3.join(dir, `${path3.basename(spec.stdoutFile, ".out")}.spawn.json`); + const specDoc = { + command: spec.command, + argv: spec.argv, + cwd: spec.cwd, + stdoutFile: spec.stdoutFile, + resultFile + }; + if (spec.persistEnv === true) specDoc.env = spec.env; + writeJsonAtomic(specFile, specDoc); + const helper = process.env.TEAM_DETACH_HELPER ?? HELPER_DEFAULT; + await new Promise((resolve, reject) => { + execFile( + process.execPath, + ["--", helper, specFile], + { timeout: SPAWN_HELPER_TIMEOUT_MS, cwd: spec.cwd, env: spec.env }, + (err) => { + if (err) reject(new Error(`detach helper failed: ${err.message}`)); + else resolve(); + } + ); + }); + let result; + try { + result = JSON.parse(fs3.readFileSync(resultFile, "utf8")); + } catch (err) { + throw new Error(`detach helper produced no result file: ${err instanceof Error ? err.message : String(err)}`); + } + if (typeof result.error === "string") { + throw new Error(`turn process launch failed: ${result.error}`); + } + return { pid: result.pid ?? null, pgid: result.pid ?? null, stdoutFile: spec.stdoutFile, specFile, resultFile }; +} +function pidAlive(pid) { + if (pid === null || !Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return err.code === "EPERM"; + } +} +function pgidAlive(pgid) { + if (pgid === null || !Number.isInteger(pgid) || pgid <= 0) return false; + try { + process.kill(-pgid, 0); + return true; + } catch (err) { + return err.code === "EPERM"; + } +} +async function killProcessGroup(pgid, graceMs, signal) { + signal?.throwIfAborted(); + if (pgid === null || pgid <= 0) return true; + signalGroup(pgid, "SIGTERM"); + for (let waited = 0; waited < graceMs; waited += 50) { + await sleep(50); + signal?.throwIfAborted(); + if (!pgidAlive(pgid) && !pidAlive(pgid)) return true; + } + signal?.throwIfAborted(); + if (pgidAlive(pgid) || pidAlive(pgid)) { + signalGroup(pgid, "SIGKILL"); + for (let waited = 0; waited < 2e3; waited += 50) { + await sleep(50); + signal?.throwIfAborted(); + if (!pgidAlive(pgid) && !pidAlive(pgid)) return true; + } + } + return !pgidAlive(pgid) && !pidAlive(pgid); +} +function signalGroup(pgid, sig) { + try { + process.kill(-pgid, sig); + } catch (err) { + if (err.code !== "ESRCH") { + throw err; + } + } +} +function sleep(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// src/coord/lock.ts +var DEFAULT_LOCK_TUNING = { + heartbeatMs: 1e3, + expiryMs: 4500, + pollMs: 200, + graceMs: 3e3, + hardExpiryMs: 15e3 +}; +var exitReleases = /* @__PURE__ */ new Set(); +var exitHookInstalled = false; +function registerExitRelease(release) { + exitReleases.add(release); + if (!exitHookInstalled) { + exitHookInstalled = true; + process.once("exit", () => { + for (const fn of [...exitReleases]) { + try { + fn(); + } catch { + } + } + exitReleases.clear(); + }); + } + return () => exitReleases.delete(release); +} +var AcquireTimeout = class extends Error { + constructor(message) { + super(message); + this.name = "AcquireTimeout"; + } +}; +function heartbeatFileFor(lockFile, token) { + return `${lockFile}.hb-${token}`; +} +var CoordinatorLock = class { + lockFile; + auditFile; + tuning; + ownerBootId; + onLost; + held = null; + heartbeatTimer = null; + exitUnregister = null; + constructor(lockFile, auditFile, opts = {}) { + this.lockFile = lockFile; + this.auditFile = auditFile; + const { ownerBootId, onLost, ...tuning } = opts; + this.tuning = { ...DEFAULT_LOCK_TUNING, ...tuning }; + this.ownerBootId = ownerBootId ?? bootId(); + this.onLost = onLost; + } + get info() { + return this.held?.info ?? null; + } + get isHeld() { + return this.held !== null; + } + get tuningOptions() { + return { ...this.tuning }; + } + /** + * 抢锁(原子):O_EXCL 创建 owner 文件即持有。已存在时——新鲜则等待重试,过期 + * (心跳龄 > expiryMs;不可解析按 mtime)则经 guard 复核后 quarantine 再重抢。 + * waitMs 内未获得 → AcquireTimeout(所有分支都受 deadline 约束)。 + */ + async acquire(opts = {}) { + const waitMs = opts.waitMs ?? 0; + const deadline = Date.now() + waitMs; + const timeout = () => { + throw new AcquireTimeout(`coordinator lock not acquired within ${waitMs}ms (holder alive)`); + }; + for (; ; ) { + const claimed = await this.tryClaim(); + if (claimed !== null) return claimed; + const observed = this.observe(); + if (!observed.exists) { + if (Date.now() >= deadline) timeout(); + await sleep2(1); + continue; + } + if (observed.ageMs > this.tuning.expiryMs) { + const outcome = await this.steal(observed); + if (outcome === "stolen") continue; + if (Date.now() >= deadline) timeout(); + await sleep2(Math.min(this.tuning.pollMs, Math.max(deadline - Date.now(), 1))); + continue; + } + if (Date.now() >= deadline) timeout(); + await sleep2(Math.min(this.tuning.pollMs, Math.max(deadline - Date.now(), 1))); + } + } + /** 续持:owner inode + token 双 CAS 通过后写心跳;被抢/丢失 → false(onLost 恰一次)。 */ + async renew() { + const held = this.held; + if (held === null) return false; + const owner = this.readOwner(); + if (owner === null || owner.info.token !== held.token || owner.ino !== held.ino || owner.info.pid !== process.pid || owner.info.bootId !== this.ownerBootId) { + this.markLost(owner?.info ?? held.info); + return false; + } + const now2 = Date.now(); + try { + this.writeHeartbeat(held.token, now2); + } catch (err) { + try { + this.writeHeartbeat(held.token, now2); + } catch (retryErr) { + this.audit("renew-failed", { error: String(err), retryError: String(retryErr) }); + this.markLost(owner.info); + return false; + } + } + this.held = { ...held, info: { ...held.info, heartbeatAt: now2 } }; + return true; + } + /** 同步释放(exit handler 用;预算 ≤200ms)。只删 inode+token 均为自己的 owner 文件。 */ + releaseSync() { + this.stopHeartbeat(); + if (this.exitUnregister !== null) { + this.exitUnregister(); + this.exitUnregister = null; + } + const held = this.held; + this.held = null; + if (held === null) return; + try { + const fd = fs4.openSync(this.lockFile, "r"); + try { + const stat = fs4.fstatSync(fd); + if (stat.ino !== held.ino) { + this.audit("release-skip", { reason: "inode-changed", expected: held.ino, actual: stat.ino }); + return; + } + const info = JSON.parse(fs4.readFileSync(fd, "utf8")); + if (info.token !== held.token || info.pid !== process.pid || info.bootId !== this.ownerBootId) { + this.audit("release-skip", { reason: "owner-changed", previous: info }); + return; + } + } finally { + fs4.closeSync(fd); + } + if (fs4.statSync(this.lockFile).ino !== held.ino) { + this.audit("release-skip", { reason: "inode-changed-before-unlink" }); + return; + } + fs4.unlinkSync(this.lockFile); + this.audit("release", { via: "exit-handler" }); + } catch (err) { + if (err.code === "ENOENT") return; + this.audit("release-failed", { error: String(err) }); + } finally { + this.removeHeartbeat(held.token); + } + } + async release() { + this.releaseSync(); + } + startHeartbeat() { + this.stopHeartbeat(); + this.heartbeatTimer = setInterval(() => { + void this.renew().catch(() => { + }); + }, this.tuning.heartbeatMs); + this.heartbeatTimer.unref?.(); + } + stopHeartbeat() { + if (this.heartbeatTimer !== null) { + clearInterval(this.heartbeatTimer); + this.heartbeatTimer = null; + } + } + /** 注册 exit handler(幂等):进程退出时 best-effort 释放(单例监听器注册表)。 */ + installExitHandlers() { + if (this.exitUnregister !== null) return; + this.exitUnregister = registerExitRelease(() => this.releaseSync()); + } + /** 观察锁文件(不抢)。ageMs:可解析 = now-heartbeatAt(优先 token 心跳);否则 now-mtime。 + * 〔D32〕同时给出持有者进程存活信号与心跳来源(回退路径不再静默不可诊断)。 */ + observe() { + let raw; + let stat; + try { + stat = fs4.statSync(this.lockFile); + raw = fs4.readFileSync(this.lockFile, "utf8"); + } catch { + return { exists: false, ageMs: Number.POSITIVE_INFINITY, parseable: false, holderAlive: null, hbSource: "mtime" }; + } + try { + const info = JSON.parse(raw); + if (typeof info.pid === "number" && typeof info.bootId === "string" && typeof info.heartbeatAt === "number") { + let heartbeatAt = info.heartbeatAt; + let hbSource = "owner-fallback"; + if (typeof info.token === "string") { + const hb = this.readHeartbeat(info.token); + if (hb !== void 0) { + heartbeatAt = hb; + hbSource = "token"; + } + } + return { + exists: true, + info, + ageMs: Date.now() - heartbeatAt, + parseable: true, + ino: stat.ino, + holderAlive: pidAlive(info.pid), + hbSource + }; + } + } catch { + } + return { + exists: true, + ageMs: Date.now() - stat.mtimeMs, + parseable: false, + ino: stat.ino, + holderAlive: null, + hbSource: "mtime" + }; + } + /** 审计痕迹(获取/释放/抢占/丢失;best-effort,无 fsync)。 */ + audit(event, detail) { + if (this.auditFile === void 0) return; + try { + fs4.mkdirSync(path4.dirname(this.auditFile), { recursive: true }); + fs4.appendFileSync( + this.auditFile, + JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), event, pid: process.pid, bootId: this.ownerBootId, detail }) + "\n", + { mode: 384 } + ); + } catch { + } + } + async tryClaim() { + const now2 = Date.now(); + const token = crypto2.randomBytes(12).toString("hex"); + const info = { + pid: process.pid, + bootId: this.ownerBootId, + heartbeatAt: now2, + acquiredAt: now2, + // 〔D32〕进程启动时刻估算(宽限路径做 PID 复用防护;旧锁无此字段则跳过校验)。 + startedAt: now2 - Math.round(process.uptime() * 1e3), + token + }; + let fd; + try { + fd = fs4.openSync(this.lockFile, "wx", 384); + } catch (err) { + if (err.code === "EEXIST") return null; + throw err; + } + let ino; + try { + fs4.writeFileSync(fd, JSON.stringify(info)); + fs4.fsyncSync(fd); + ino = fs4.fstatSync(fd).ino; + } catch (err) { + try { + const stat = fs4.fstatSync(fd); + if (stat.ino === fs4.statSync(this.lockFile).ino) fs4.unlinkSync(this.lockFile); + } catch { + } + throw err; + } finally { + fs4.closeSync(fd); + } + this.held = { info, token, ino }; + try { + this.writeHeartbeat(token, now2); + this.cleanupForeignHeartbeats(token); + } catch (err) { + this.audit("heartbeat-first-write-failed", { error: String(err) }); + } + this.audit("acquire", { token: token.slice(0, 8), ino }); + return info; + } + readOwner() { + try { + const fd = fs4.openSync(this.lockFile, "r"); + try { + const stat = fs4.fstatSync(fd); + const info = JSON.parse(fs4.readFileSync(fd, "utf8")); + return { info, ino: stat.ino }; + } finally { + fs4.closeSync(fd); + } + } catch { + return null; + } + } + readHeartbeat(token) { + try { + const parsed = JSON.parse(fs4.readFileSync(heartbeatFileFor(this.lockFile, token), "utf8")); + if (parsed.token === token && typeof parsed.heartbeatAt === "number") return parsed.heartbeatAt; + } catch { + } + return void 0; + } + writeHeartbeat(token, at) { + const file = heartbeatFileFor(this.lockFile, token); + const tmp = `${file}.tmp-${process.pid}-${crypto2.randomBytes(4).toString("hex")}`; + try { + fs4.writeFileSync(tmp, JSON.stringify({ token, heartbeatAt: at }), { mode: 384 }); + fs4.renameSync(tmp, file); + } catch (err) { + try { + fs4.unlinkSync(tmp); + } catch { + } + throw err; + } + } + removeHeartbeat(token) { + try { + fs4.unlinkSync(heartbeatFileFor(this.lockFile, token)); + } catch { + } + } + cleanupForeignHeartbeats(ownToken) { + let names; + try { + names = fs4.readdirSync(path4.dirname(this.lockFile)); + } catch { + return; + } + const prefix = `${path4.basename(this.lockFile)}.hb-`; + for (const name of names) { + if (!name.startsWith(prefix) || name === `${prefix}${ownToken}`) continue; + try { + fs4.unlinkSync(path4.join(path4.dirname(this.lockFile), name)); + } catch { + } + } + } + /** + * 过期接任(保守唯一写者):只有确认持有者退出或 PID 已复用才隔离旧锁。 + * 活进程/不可解析持有者的写能力无法由文件锁撤销,超龄也绝不抢占;等待其正常释放。 + * 若 rename 到的不是观察到的 inode(竞争者刚换了新锁)→ 尝试归还并回滚。 + */ + async steal(observed) { + const guard = `${this.lockFile}.guard-${process.pid}-${crypto2.randomBytes(4).toString("hex")}`; + let guardFd; + try { + guardFd = fs4.openSync(guard, "wx", 384); + } catch (err) { + if (err.code === "EEXIST") return "skipped"; + throw err; + } + try { + const current = this.observe(); + if (!current.exists || current.ageMs <= this.tuning.expiryMs) return "skipped"; + if (observed.ino === void 0 || current.ino !== observed.ino || current.info?.token !== observed.info?.token) { + return "skipped"; + } + if (current.holderAlive !== false && !this.pidReused(current)) { + this.audit("steal-deferred", { + reason: current.holderAlive === true ? "holder-alive" : "holder-liveness-unknown", + ageMs: Math.round(current.ageMs), + hbSource: current.hbSource, + previous: current.info + }); + return "deferred"; + } + const quarantine = `${this.lockFile}.stale-${Date.now()}-${crypto2.randomBytes(4).toString("hex")}`; + try { + fs4.renameSync(this.lockFile, quarantine); + } catch (err) { + if (err.code === "ENOENT") return "skipped"; + throw err; + } + let quarantinedIno = null; + try { + quarantinedIno = fs4.statSync(quarantine).ino; + } catch { + quarantinedIno = null; + } + if (quarantinedIno !== current.ino) { + try { + fs4.linkSync(quarantine, this.lockFile); + fs4.unlinkSync(quarantine); + this.audit("steal-rollback", { reason: "inode-mismatch", quarantinedIno, expected: current.ino }); + } catch (rollbackErr) { + this.audit("steal-rollback-failed", { + reason: "inode-mismatch", + quarantinedIno, + expected: current.ino, + error: String(rollbackErr), + quarantine + }); + } + return "skipped"; + } + this.audit("steal", { + reason: current.parseable ? "heartbeat-expired" : "unparseable-and-aged", + holderAlive: current.holderAlive, + hbSource: current.hbSource, + previous: current.info ?? { mtimeAgeMs: Math.round(current.ageMs) }, + quarantine + }); + if (typeof current.info?.token === "string") this.removeHeartbeat(current.info.token); + return "stolen"; + } finally { + try { + fs4.closeSync(guardFd); + } catch { + } + try { + fs4.unlinkSync(guard); + } catch { + } + } + } + /** + * 〔D32〕PID 复用防护(仅宽限路径调用):锁内 startedAt 与 `ps -o etime=` 推算的启动时刻 + * 偏差 >3s → 认定 PID 已被复用(原持有者已死)→ 跳过宽限按死亡处理。 + * 旧锁无 startedAt / ps 不可用 / 解析失败 → 返回 false(保守:维持宽限,不误杀活人)。 + * etime 跨平台(macOS 无 etimes;格式 mm:ss | hh:mm:ss | d-hh:mm:ss)。 + */ + pidReused(observed) { + const startedAt = observed.info?.startedAt; + const pid = observed.info?.pid; + if (typeof startedAt !== "number" || typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) { + return false; + } + const r = spawnSync("ps", ["-o", "etime=", "-p", String(pid)], { encoding: "utf8" }); + if (r.status !== 0) return false; + const elapsedSec = parseEtime(r.stdout.trim()); + if (!Number.isFinite(elapsedSec) || elapsedSec < 0) return false; + const estimatedStart = Date.now() - elapsedSec * 1e3; + return Math.abs(estimatedStart - startedAt) > 3e3; + } + markLost(previous) { + if (this.held === null) return; + this.audit("lost", { previous }); + this.held = null; + this.stopHeartbeat(); + this.onLost?.({ previous }); + } +}; +function sleep2(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} +function parseEtime(raw) { + let s = raw.trim(); + if (s.length === 0) return Number.NaN; + let days = 0; + const dash = s.indexOf("-"); + if (dash !== -1) { + days = Number.parseInt(s.slice(0, dash), 10); + s = s.slice(dash + 1); + } + const parts = s.split(":").map((p) => Number.parseInt(p, 10)); + if (parts.some((p) => !Number.isFinite(p) || p < 0)) return Number.NaN; + let sec; + if (parts.length === 3) sec = parts[0] * 3600 + parts[1] * 60 + parts[2]; + else if (parts.length === 2) sec = parts[0] * 60 + parts[1]; + else return Number.NaN; + return days * 86400 + sec; +} + +// src/coord/journal.ts +import fs7 from "node:fs"; +import path6 from "node:path"; + +// src/domain/events.ts +var IMAGE_MEDIA_TYPES = ["png", "jpeg", "webp", "gif"]; +function validateContentBlock(block) { + if (typeof block !== "object" || block === null || Array.isArray(block)) { + throw new Error("content block must be a JSON object"); + } + const b = block; + switch (b.type) { + case "text": + case "reasoning": + if (typeof b.text !== "string") throw new Error(`${String(b.type)} block requires string text`); + return block; + case "image": { + const a = b.attachment; + if (typeof a !== "object" || a === null || Array.isArray(a)) { + throw new Error("image block requires object attachment"); + } + const att = a; + if (typeof att.attachmentId !== "string") throw new Error("image attachment requires string attachmentId"); + if (typeof att.mediaType !== "string" || !IMAGE_MEDIA_TYPES.includes(att.mediaType)) { + throw new Error(`image attachment mediaType must be one of ${IMAGE_MEDIA_TYPES.join("/")}`); + } + if (typeof att.bytes !== "number") throw new Error("image attachment requires number bytes"); + if (typeof att.width !== "number") throw new Error("image attachment requires number width"); + if (typeof att.height !== "number") throw new Error("image attachment requires number height"); + if (att.name !== void 0 && typeof att.name !== "string") { + throw new Error("image attachment name must be a string when present"); + } + return block; + } + case "tool-call": { + if (typeof b.id !== "string") throw new Error("tool-call block requires string id"); + if (typeof b.name !== "string") throw new Error("tool-call block requires string name"); + if (!("arguments" in b)) throw new Error("tool-call block requires arguments"); + return block; + } + case "tool-result": + throw new Error("retired tool-result wrapper is not accepted as Team message content"); + default: + return block; + } +} +var contentBlocksSchema = external_exports.array(external_exports.unknown()).superRefine((blocks, ctx) => { + for (let i = 0; i < blocks.length; i++) { + try { + validateContentBlock(blocks[i]); + } catch (err) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: [i], + message: err instanceof Error ? err.message : String(err) + }); + } + } +}); +var TASK_ID_PATTERN = /^task-(\d+)$/; +function isLooseIdValid(id) { + if (id.length === 0) return false; + const m = id.match(TASK_ID_PATTERN); + if (m && !Number.isSafeInteger(Number(m[1]))) return false; + return true; +} +function taskNumberFromId(id) { + const m = id.match(TASK_ID_PATTERN); + return m ? Number(m[1]) : void 0; +} +var looseIdSchema = external_exports.string().refine(isLooseIdValid, { message: "invalid loose id" }); +var memberSnapshotSchema = external_exports.strictObject({ + id: external_exports.string(), + name: external_exports.string(), + description: external_exports.string(), + provider: external_exports.string(), + context: external_exports.enum(["fresh", "fork"]), + phase: external_exports.enum(["provisioning", "active", "failed"]), + error: external_exports.string().optional() +}); +var taskSnapshotSchema = external_exports.strictObject({ + id: looseIdSchema, + revision: external_exports.number().refine((n) => Number.isSafeInteger(n) && n >= 1, { + message: "revision must be a positive safe integer" + }), + subject: external_exports.string(), + description: external_exports.string(), + status: external_exports.enum(["pending", "in_progress", "completed", "deleted"]), + ownerId: external_exports.string().optional(), + blockedBy: external_exports.array(external_exports.string()), + writeScopes: external_exports.array(external_exports.string()) +}); +var messageSnapshotSchema = external_exports.strictObject({ + id: looseIdSchema, + senderId: external_exports.string(), + senderName: external_exports.string(), + targetId: external_exports.string(), + content: contentBlocksSchema +}); +var TEAM_EVENT_VERSION = 2; +var TEAM_EVENT_TYPES = [ + "team/member", + "team/task", + "team/message/queued", + "team/message/delivered" +]; +var memberEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/member"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + member: memberSnapshotSchema +}); +var taskEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/task"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + task: taskSnapshotSchema +}); +var messageQueuedEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/message/queued"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + message: messageSnapshotSchema +}); +var messageDeliveredEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/message/delivered"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + messageId: external_exports.string(), + targetId: external_exports.string() +}); +var TEAM_EVENT_SCHEMAS = { + "team/member": memberEventSchema, + "team/task": taskEventSchema, + "team/message/queued": messageQueuedEventSchema, + "team/message/delivered": messageDeliveredEventSchema +}; +var LEGACY_EVENT_TYPE_ALIASES = { + "team/message": "team/message/queued" +}; +function selectTeamEvent(raw, teamId) { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { kind: "ignored" }; + const candidate = raw; + const rawType = candidate.type; + if (typeof rawType !== "string") return { kind: "ignored" }; + const eventType = TEAM_EVENT_TYPES.includes(rawType) ? rawType : LEGACY_EVENT_TYPE_ALIASES[rawType]; + if (eventType === void 0) return { kind: "ignored" }; + if (typeof candidate.teamId !== "string" || candidate.teamId !== teamId) { + return { kind: "ignored" }; + } + if (candidate.version !== TEAM_EVENT_VERSION) { + return { kind: "unsupported-version", version: candidate.version }; + } + const normalized = rawType === eventType ? raw : { ...candidate, type: eventType }; + const parsed = TEAM_EVENT_SCHEMAS[eventType].safeParse(normalized); + if (!parsed.success) return { kind: "invalid-payload", type: eventType }; + return { kind: "event", event: parsed.data }; +} +var deliveredIdsSchema = external_exports.preprocess((value) => { + if (!Array.isArray(value)) return value; + return value.map((item) => { + if (typeof item === "string") return item; + if (typeof item === "object" && item !== null && typeof item.messageId === "string") { + return item.messageId; + } + return item; + }); +}, external_exports.array(external_exports.string())); +var teamStateSchema = external_exports.strictObject({ + id: external_exports.string(), + members: external_exports.array(memberSnapshotSchema), + tasks: external_exports.array(taskSnapshotSchema), + messages: external_exports.array(messageSnapshotSchema), + delivered: deliveredIdsSchema, + nextTaskNumber: external_exports.number().refine((n) => Number.isSafeInteger(n) && n >= 1, { + message: "nextTaskNumber must be a positive safe integer" + }), + failure: external_exports.string().optional() +}); + +// src/domain/task-graph.ts +function validateTaskGraph(tasks) { + const byId = new Map(tasks.map((t) => [t.id, t])); + const live = tasks.filter((t) => t.status !== "deleted"); + for (const task of live) { + for (const bid of task.blockedBy) { + if (bid === task.id) { + throw new Error(`team task "${task.id}" cannot block itself`); + } + } + } + for (const task of live) { + const seen = /* @__PURE__ */ new Set(); + for (const bid of task.blockedBy) { + if (seen.has(bid)) { + throw new Error(`team task "${task.id}" repeats blocker "${bid}"`); + } + seen.add(bid); + } + } + for (const task of live) { + for (const bid of task.blockedBy) { + const blocker = byId.get(bid); + if (blocker === void 0 || blocker.status === "deleted") { + throw new Error(`blocker task "${bid}" for "${task.id}" is missing or deleted`); + } + } + } + detectCycle(live, byId); +} +function detectCycle(live, byId) { + const WHITE = 0; + const GRAY = 1; + const BLACK = 2; + const color = /* @__PURE__ */ new Map(); + const visit = (task) => { + color.set(task.id, GRAY); + for (const bid of task.blockedBy) { + const blocker = byId.get(bid); + if (blocker === void 0 || blocker.status === "deleted") continue; + const c = color.get(bid) ?? WHITE; + if (c === GRAY) { + throw new Error(`task dependency cycle includes "${bid}"`); + } + if (c === WHITE) visit(blocker); + } + color.set(task.id, BLACK); + }; + for (const task of live) { + if ((color.get(task.id) ?? WHITE) === WHITE) visit(task); + } +} +function assertTaskGraphCandidate(existing, candidate) { + const tasks = existing.some((t) => t.id === candidate.id) ? existing.map((t) => t.id === candidate.id ? candidate : t) : [...existing, candidate]; + try { + validateTaskGraph(tasks); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + if (message.includes("cannot block itself") || message.includes("task dependency cycle")) { + throw new TeamError("TEAM_TASK_DEPENDENCY_CYCLE", message); + } + if (message.includes("repeats blocker")) { + throw new TeamError("TEAM_INVALID_ARGUMENT", message); + } + if (message.includes("missing or deleted")) { + throw new TeamError("TEAM_TASK_NOT_FOUND", message); + } + throw err; + } +} +function dependencies(existingTasks, taskId, blockedBy) { + const seen = /* @__PURE__ */ new Set(); + for (const bid of blockedBy) { + if (bid === taskId) { + throw new TeamError("TEAM_TASK_DEPENDENCY_CYCLE", "a team task cannot block itself", { + cause: { taskId, blocker: bid } + }); + } + if (seen.has(bid)) { + throw new TeamError("TEAM_INVALID_ARGUMENT", `duplicate blocker "${bid}"`, { + cause: { taskId, blocker: bid } + }); + } + seen.add(bid); + const blocker = existingTasks.find((t) => t.id === bid); + if (blocker === void 0 || blocker.status === "deleted") { + throw new TeamError("TEAM_TASK_NOT_FOUND", `blocker task "${bid}" not found`, { + cause: { taskId, blocker: bid } + }); + } + } +} + +// src/domain/task-view.ts +function taskReady(state, task) { + return task.blockedBy.every((bid) => { + const blocker = state.tasks.find((t) => t.id === bid); + return blocker !== void 0 && blocker.status === "completed"; + }); +} +function projectTaskView(state, task) { + const view2 = { + id: task.id, + revision: task.revision, + subject: task.subject, + description: task.description, + status: task.status, + blockedBy: [...task.blockedBy], + writeScopes: [...task.writeScopes], + ready: task.status === "pending" && taskReady(state, task), + writeScopeWarnings: writeScopeWarnings(state, task) + }; + if (task.ownerId !== void 0) { + const ownerName = task.ownerId === state.id ? "lead" : state.members.find((m) => m.id === task.ownerId)?.name; + if (ownerName !== void 0) view2.ownerName = ownerName; + } + return view2; +} +function writeScopeWarnings(state, task) { + if (task.status !== "in_progress") return []; + const warnings = /* @__PURE__ */ new Set(); + for (const other of state.tasks) { + if (other.id === task.id || other.status !== "in_progress") continue; + if (scopesOverlap(task.writeScopes, other.writeScopes)) { + warnings.add(`write scopes overlap with ${other.id}`); + } + } + return [...warnings]; +} +function scopesOverlap(left, right) { + for (const l of left) { + for (const r of right) { + if (l === r || l.startsWith(r + "/") || r.startsWith(l + "/")) return true; + } + } + return false; +} + +// src/domain/projection.ts +var TEAM_PROJECTION_STATE_VERSION = 4; +function emptyTeamState(rootId) { + return { + id: rootId, + members: [], + tasks: [], + messages: [], + delivered: [], + nextTaskNumber: 1 + }; +} +function failed(state, failure) { + return { ...state, failure }; +} +function applyProjectionEvent(state, raw) { + if (state.failure !== void 0) return state; + const selected = selectTeamEvent(raw, state.id); + switch (selected.kind) { + case "ignored": + return state; + case "unsupported-version": + return failed(state, `unsupported Agent Teams event version ${String(selected.version)}`); + case "invalid-payload": + return failed(state, `persisted Agent Teams ${selected.type} payload is invalid`); + case "event": + return applyCurrentTeamEvent(state, selected.event); + } +} +function applyCurrentTeamEvent(state, event) { + if (state.failure !== void 0) return state; + switch (event.type) { + case "team/member": + return applyMember(state, event.member); + case "team/task": + return applyTask(state, event.task); + case "team/message/queued": + return applyMessageQueued(state, event.message); + case "team/message/delivered": + return applyMessageDelivered(state, event.messageId, event.targetId); + } +} +function applyMember(state, member) { + const prior = state.members.find((m) => m.id === member.id); + if (prior === void 0) { + if (member.phase !== "provisioning") { + return failed(state, `teammate "${member.name}" must begin provisioning`); + } + if (state.members.some((m) => m.name === member.name)) { + return failed(state, `teammate name "${member.name}" is reused by another member`); + } + return { ...state, members: [...state.members, member] }; + } + if (prior.name !== member.name || prior.provider !== member.provider || prior.context !== member.context) { + return failed(state, `teammate "${prior.id}" changed immutable identity fields`); + } + if (prior.phase !== "provisioning" || member.phase !== "active" && member.phase !== "failed") { + return failed( + state, + `teammate "${member.name}" has an invalid ${prior.phase} -> ${member.phase} transition` + ); + } + return { ...state, members: state.members.map((m) => m.id === member.id ? member : m) }; +} +function applyTask(state, task) { + const prior = state.tasks.find((t) => t.id === task.id); + const expectedRevision = prior === void 0 ? 1 : prior.revision + 1; + if (task.revision !== expectedRevision) { + return failed( + state, + prior === void 0 ? `team task "${task.id}" must begin at revision 1` : `team task "${task.id}" revision is not contiguous` + ); + } + const tasks = prior === void 0 ? [...state.tasks, task] : state.tasks.map((t) => t.id === task.id ? task : t); + try { + validateTaskGraph(tasks); + } catch (err) { + return failed(state, err instanceof Error ? err.message : String(err)); + } + let nextTaskNumber = state.nextTaskNumber; + const n = taskNumberFromId(task.id); + if (n !== void 0) { + nextTaskNumber = Math.max(state.nextTaskNumber, Math.min(n + 1, Number.MAX_SAFE_INTEGER)); + } + return { ...state, tasks, nextTaskNumber }; +} +function applyMessageQueued(state, message) { + if (state.messages.some((m) => m.id === message.id)) { + return failed(state, `team message "${message.id}" was queued twice`); + } + return { ...state, messages: [...state.messages, message] }; +} +function applyMessageDelivered(state, messageId, targetId) { + const queued = state.messages.find((m) => m.id === messageId); + if (queued === void 0) { + return failed(state, `team message "${messageId}" was delivered before queueing`); + } + if (queued.targetId !== targetId) { + return failed(state, `team message "${messageId}" target changed`); + } + if (state.delivered.includes(messageId)) { + return failed(state, `team message "${messageId}" was delivered twice`); + } + return { ...state, delivered: [...state.delivered, messageId] }; +} +var viewCache = /* @__PURE__ */ new WeakMap(); +function teamProjectionView(state) { + let byTasks = viewCache.get(state.members); + if (byTasks === void 0) { + byTasks = /* @__PURE__ */ new WeakMap(); + viewCache.set(state.members, byTasks); + } + let entry = byTasks.get(state.tasks); + if (entry === void 0) { + const members = [ + { id: state.id, name: "lead", role: "lead", phase: "active" }, + ...state.members.map((m) => ({ id: m.id, name: m.name, role: "teammate", phase: m.phase, ...m.error !== void 0 ? { error: m.error } : {} })) + ]; + const tasks = state.tasks.filter((t) => t.status !== "deleted").map((t) => projectTaskView(state, t)); + entry = { healthy: { members, tasks } }; + byTasks.set(state.tasks, entry); + } + if (state.failure === void 0) return entry.healthy; + if (entry.failed === void 0) { + entry.failed = { ...entry.healthy, failure: state.failure }; + } + return entry.failed; +} +function tryMembership(loadState, agentId) { + let state; + try { + state = loadState(); + } catch { + return void 0; + } + if (agentId === state.id) { + return { rootId: state.id, role: "lead", name: "lead" }; + } + const member = state.members.find((m) => m.id === agentId); + if (member !== void 0 && (member.phase === "active" || member.phase === "provisioning")) { + return { rootId: state.id, role: "teammate", name: member.name }; + } + return void 0; +} +function requireMembership(loadState, agentId) { + const membership = tryMembership(loadState, agentId); + if (membership === void 0) { + throw new TeamError( + "TEAM_NOT_MEMBER", + `agent "${agentId}" is not a member of an active Agent Team` + ); + } + return membership; +} +function projectionFailureError(failure) { + return new Error(failure); +} + +// src/domain/invariant.ts +function assertAppendable(teamId, committed, candidate) { + let state = emptyTeamState(teamId); + for (let i = 0; i < committed.length; i++) { + const next = applyProjectionEvent(state, committed[i]); + if (next.failure !== void 0) { + throw new Error( + `session event ${i + 1} violates the Agent Teams stream: ${next.failure}` + ); + } + state = next; + } + const withCandidate = applyProjectionEvent(state, candidate); + if (withCandidate.failure !== void 0) { + throw new Error( + `session event ${committed.length + 1} violates the Agent Teams stream: ${withCandidate.failure}` + ); + } +} + +// src/coord/lockfile.ts +import fs5 from "node:fs"; +function observeLockFileFor(lockFile, writer) { + const identity = parseWriterId(writer); + if (identity === void 0) { + return { ok: false, reason: `writer id "${writer}" is malformed` }; + } + let raw; + try { + raw = fs5.readFileSync(lockFile, "utf8"); + } catch (err) { + return { ok: false, reason: `lock unreadable: ${err.code ?? String(err)}` }; + } + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + return { ok: false, reason: "lock file is not valid JSON" }; + } + if (parsed.pid !== identity.pid || parsed.bootId !== identity.bootId || identity.token !== void 0 && parsed.token !== identity.token) { + return { + ok: false, + reason: `lock held by pid=${String(parsed.pid)} bootId=${String(parsed.bootId)}` + }; + } + return { ok: true, reason: "owned" }; +} + +// src/coord/replay.ts +import fs6 from "node:fs"; +import path5 from "node:path"; +var checkpointDocSchema = external_exports.strictObject({ + kind: external_exports.literal("agent-team-checkpoint"), + stateVersion: external_exports.literal(TEAM_PROJECTION_STATE_VERSION), + lastSeq: external_exports.number().int().nonnegative(), + lastOffset: external_exports.number().int().nonnegative(), + savedAt: external_exports.string(), + state: teamStateSchema, + view: external_exports.unknown() +}); +function checkpointPath(teamDir) { + return path5.join(teamDir, "checkpoint.json"); +} +async function load(teamDir, teamId) { + const startedAt = Date.now(); + const eventsFile = path5.join(teamDir, "events.jsonl"); + const raw = readBufferOrEmpty(eventsFile); + let checkpointIgnored; + let doc; + try { + const rawDoc = fs6.readFileSync(checkpointPath(teamDir), "utf8"); + const parsed = checkpointDocSchema.safeParse(JSON.parse(rawDoc)); + if (!parsed.success) { + checkpointIgnored = `checkpoint invalid: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`; + } else if (parsed.data.state.id !== teamId) { + checkpointIgnored = `checkpoint teamId mismatch (${parsed.data.state.id} != ${teamId})`; + } else { + doc = parsed.data; + } + } catch { + } + const writers = []; + let state = emptyTeamState(teamId); + let seq = 0; + let fromCheckpoint = false; + let corrupt; + if (doc !== void 0) { + const tail = raw.subarray(doc.lastOffset); + const first = firstLineBytes(tail); + if (tail.length > 0 && first === void 0) { + checkpointIgnored = "checkpoint offset desync (tail not line-aligned) \u2014 full replay"; + } else if (first !== void 0 && JSON.parse(first.parsed).seq !== doc.lastSeq + 1) { + checkpointIgnored = "checkpoint offset desync (seq continuity broken) \u2014 full replay"; + } else { + state = doc.state; + seq = doc.lastSeq; + fromCheckpoint = true; + } + } + const startOffset = fromCheckpoint && doc !== void 0 ? doc.lastOffset : 0; + let offset = startOffset; + let consumeRest = true; + while (consumeRest && offset < raw.length) { + const nl = raw.indexOf(10, offset); + if (nl === -1) { + corrupt = { line: seq + 1, reason: "trailing partial line (no newline)" }; + state = withFailure(state, raw.subarray(offset).toString("utf8")); + seq += 1; + consumeRest = false; + break; + } + const lineText = raw.subarray(offset, nl).toString("utf8"); + const lineNo = seq + 1; + offset = nl + 1; + if (lineText.length === 0) { + corrupt = { line: lineNo, reason: "empty line" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + let parsed; + try { + parsed = JSON.parse(lineText); + } catch { + corrupt = { line: lineNo, reason: "invalid JSON" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + const line = parsed; + if (typeof line.writer === "string" && !writers.includes(line.writer)) writers.push(line.writer); + if (typeof parsed !== "object" || parsed === null || typeof parsed.seq !== "number" || !("event" in parsed) || parsed.seq !== lineNo) { + corrupt = { line: lineNo, reason: "line shape invalid or seq discontinuous" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + state = applyProjectionEvent(state, line.event); + seq = lineNo; + if (state.failure !== void 0) { + consumeRest = false; + } + } + return { + state, + view: teamProjectionView(state), + seq, + fromCheckpoint, + checkpointIgnored, + corrupt, + writers, + replayMs: Date.now() - startedAt + }; +} +async function writeCheckpoint(teamDir, input) { + const eventsFile = path5.join(teamDir, "events.jsonl"); + const byteOffset = input.byteOffset ?? countBytesOfLines(eventsFile, input.seq); + const doc = { + kind: "agent-team-checkpoint", + stateVersion: TEAM_PROJECTION_STATE_VERSION, + lastSeq: input.seq, + lastOffset: byteOffset, + savedAt: (/* @__PURE__ */ new Date()).toISOString(), + state: input.state, + view: input.view + }; + fs6.mkdirSync(teamDir, { recursive: true, mode: 448 }); + const target = checkpointPath(teamDir); + const tmp = `${target}.tmp-${process.pid}`; + const fd = fs6.openSync(tmp, "w", 384); + try { + fs6.writeFileSync(fd, JSON.stringify(doc)); + fs6.fsyncSync(fd); + } finally { + fs6.closeSync(fd); + } + fs6.renameSync(tmp, target); +} +function readBufferOrEmpty(file) { + try { + return fs6.readFileSync(file); + } catch { + return Buffer.alloc(0); + } +} +function firstLineBytes(buf) { + const nl = buf.indexOf(10); + const first = (nl === -1 ? buf : buf.subarray(0, nl)).toString("utf8"); + if (first.length === 0) return void 0; + try { + JSON.parse(first); + return { parsed: first }; + } catch { + return void 0; + } +} +function withFailure(state, rawLine) { + const m = rawLine.match(/"type"\s*:\s*"(team\/[A-Za-z/-]+)"/); + const type = m?.[1] ?? "stream"; + return { ...state, failure: `persisted Agent Teams ${type} payload is invalid` }; +} +function countBytesOfLines(eventsFile, seq) { + const raw = readBufferOrEmpty(eventsFile); + let offset = 0; + for (let i = 0; i < seq; i++) { + const nl = raw.indexOf(10, offset); + if (nl === -1) return raw.length; + offset = nl + 1; + } + return offset; +} + +// src/coord/journal.ts +var TeamJournal = class _TeamJournal { + teamDir; + teamId; + eventsFile; + lockFile; + opts; + writer = null; + appendFd = null; + cache = null; + committedCount = 0; + bytesCommitted = 0; + txTail = Promise.resolve(); + txDepth = 0; + listeners = /* @__PURE__ */ new Set(); + static instances = /* @__PURE__ */ new Map(); + /** 进程内单例(同 teamDir+teamId 只允许一个实例,防同进程双写)。 */ + static open(teamDir, teamId, opts) { + const key = `${teamDir}\0${teamId}`; + const existing = _TeamJournal.instances.get(key); + if (existing) return existing; + const journal = new _TeamJournal(teamDir, teamId, opts); + _TeamJournal.instances.set(key, journal); + return journal; + } + constructor(teamDir, teamId, opts = {}) { + this.teamDir = teamDir; + this.teamId = teamId; + this.eventsFile = path6.join(teamDir, "events.jsonl"); + this.lockFile = path6.join(teamDir, "coordinator.lock"); + this.opts = { maxLineBytes: 65536, checkpointEvery: 256, enforceLock: true, ...opts }; + } + /** + * 取得写权(协调者专用):校验锁归属 + 冷启动全量/增量重放缓存状态 + 打开 O_APPEND 句柄。 + * 返回冷启动加载结果(含 checkpoint 命中信息)。 + */ + async openWriter(writer = writerId()) { + if (this.opts.enforceLock) { + const verdict = observeLockFileFor(this.lockFile, writer); + if (!verdict.ok) { + throw new Error( + `journal writer requires the coordinator lock (${verdict.reason}; writer=${writer})` + ); + } + } + const loaded = await load(this.teamDir, this.teamId); + this.writer = writer; + this.cache = loaded.state; + this.committedCount = loaded.seq; + fs7.mkdirSync(this.teamDir, { recursive: true, mode: 448 }); + this.appendFd = fs7.openSync(this.eventsFile, "a", 384); + this.bytesCommitted = fs7.statSync(this.eventsFile).size; + return loaded; + } + /** 追加前不变量 + 落盘 + fsync + 内存态推进 + 通知 + 应答。非法事件绝不落盘(硬断言)。 */ + appendAndFlush(candidate) { + return this.enqueue(async () => { + const seq = this.committedCount + 1; + if (this.opts.enforceLock && this.writer !== null) { + const verdict = observeLockFileFor(this.lockFile, this.writer); + if (!verdict.ok) { + throw new Error(`coordinator lock lost before append (${verdict.reason}; writer=${this.writer})`); + } + } + if (this.cache === null) { + const committed = (await readAllLines(this.eventsFile)).map((l) => l.event); + assertAppendable(this.teamId, committed, candidate); + } + const prior = this.cache ?? emptyTeamState(this.teamId); + const next = applyProjectionEvent(prior, candidate); + if (next.failure !== void 0) { + throw new Error( + `session event ${seq} violates the Agent Teams stream: ${next.failure}` + ); + } + this.opts.crashHook?.("append:before", { seq }); + const ts2 = (/* @__PURE__ */ new Date()).toISOString(); + const line = { seq, ts: ts2, writer: this.writer ?? writerId(), event: candidate }; + const raw = JSON.stringify(line) + "\n"; + if (Buffer.byteLength(raw) > this.opts.maxLineBytes) { + throw new Error( + `journal line exceeds ${this.opts.maxLineBytes} bytes (seq ${seq})` + ); + } + if (this.appendFd === null) throw new Error("journal writer not open (call openWriter first)"); + const lineBytes = Buffer.byteLength(raw); + fs7.writeSync(this.appendFd, raw); + this.opts.crashHook?.("append:after", { seq }); + this.opts.crashHook?.("fsync:before", { seq }); + fs7.fsyncSync(this.appendFd); + this.opts.crashHook?.("fsync:after", { seq }); + this.cache = next; + this.committedCount = seq; + this.bytesCommitted += lineBytes; + this.opts.crashHook?.("ack:before", { seq }); + for (const listener of this.listeners) listener(line, next); + void this.maybeCheckpoint(seq); + return { seq, ts: ts2, state: next }; + }); + } + /** 同 teamId 尾链串行(本实例事务队列;不同 team = 不同实例 = 可并发)。应答序 = 提交序。 */ + transact(op) { + return this.enqueue(() => Promise.resolve(op())); + } + /** 只读读取器:全量读行(不持写句柄;非协调者可用)。 */ + async readAll() { + return readAllLines(this.eventsFile); + } + onCommit(listener) { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + } + get committedSeq() { + return this.committedCount; + } + get cachedState() { + return this.cache; + } + async writeCheckpointNow() { + if (this.cache === null) return; + await writeCheckpoint(this.teamDir, { + state: this.cache, + view: teamProjectionView(this.cache), + seq: this.committedCount, + byteOffset: this.bytesCommitted + }); + } + async close(opts = {}) { + if (this.appendFd !== null) { + fs7.closeSync(this.appendFd); + this.appendFd = null; + } + if (opts.checkpoint !== false) await this.writeCheckpointNow(); + _TeamJournal.instances.delete(`${this.teamDir}\0${this.teamId}`); + } + async maybeCheckpoint(seq) { + if (this.opts.checkpointEvery <= 0) return; + if (seq % this.opts.checkpointEvery !== 0) return; + try { + await this.writeCheckpointNow(); + } catch { + } + } + /** 尾链入队:op 严格在前一事务完成后才开始;拒绝结果向调用方透传,不阻断后续事务。 + * 重入安全:当前已处于本实例事务的串行区内(txDepth>0)时直接执行(同 MemoryTeamStore 口径)。 */ + enqueue(op) { + if (this.txDepth > 0) return this.runGuarded(op); + const run = this.txTail.then( + () => this.runGuarded(op), + () => this.runGuarded(op) + ); + this.txTail = run.then( + () => void 0, + () => void 0 + ); + return run; + } + async runGuarded(op) { + this.txDepth += 1; + try { + return await op(); + } finally { + this.txDepth -= 1; + } + } +}; +async function readAllLines(eventsFile) { + let raw; + try { + raw = fs7.readFileSync(eventsFile, "utf8"); + } catch { + return []; + } + const lines = []; + for (const chunk of raw.split("\n")) { + if (chunk.length === 0) break; + lines.push(JSON.parse(chunk)); + } + return lines; +} + +// src/coord/paths.ts +import { createHash } from "node:crypto"; +import fs8 from "node:fs"; +import path7 from "node:path"; +import os2 from "node:os"; +var MAX_SOCKET_PATH = 96; +function teamPaths(dataRoot, teamId) { + const teamsRoot = path7.join(dataRoot, "teams"); + const teamDir = path7.join(teamsRoot, safeTeamId(teamId)); + return { + dataRoot, + teamId, + teamDir, + eventsFile: path7.join(teamDir, "events.jsonl"), + checkpointFile: path7.join(teamDir, "checkpoint.json"), + lockFile: path7.join(teamDir, "coordinator.lock"), + auditFile: path7.join(teamDir, "coordinator.audit.jsonl"), + socketCandidate: path7.join(teamDir, "coordinator.sock") + }; +} +function ensureTeamDir(paths) { + fs8.mkdirSync(paths.teamDir, { recursive: true, mode: 448 }); + try { + fs8.chmodSync(paths.teamDir, 448); + } catch { + } + return paths.teamDir; +} +function safeTeamId(teamId) { + const escaped = teamId.replace(/[^A-Za-z0-9._-]/g, (c) => "~" + c.codePointAt(0).toString(16)); + if (escaped === ".") return "~2e"; + if (escaped === "..") return "~2e2e"; + return escaped; +} +function resolveSocketPath(teamDir) { + const candidate = path7.join(teamDir, "coordinator.sock"); + if (candidate.length <= MAX_SOCKET_PATH) { + return { socketPath: candidate, fallback: false, registryFile: path7.join(teamDir, "socket.path") }; + } + const hash = createHash("sha256").update(candidate).digest("hex").slice(0, 16); + const tmpRoot = fs8.realpathSync(os2.tmpdir()); + const fallbackDir = path7.join(tmpRoot, "agent-team-sockets"); + fs8.mkdirSync(fallbackDir, { recursive: true, mode: 448 }); + try { + fs8.chmodSync(fallbackDir, 448); + } catch { + } + const fallbackPath = path7.join(fallbackDir, `at-${hash}.sock`); + return { socketPath: fallbackPath, fallback: true, registryFile: path7.join(teamDir, "socket.path") }; +} +function discoverSocketPath(teamDir) { + const registryFile = path7.join(teamDir, "socket.path"); + try { + const registered = fs8.readFileSync(registryFile, "utf8").trim(); + if (registered.length > 0) return registered; + } catch { + } + return resolveSocketPath(teamDir).socketPath; +} +function writeSocketRegistry(teamDir, socketPath) { + fs8.mkdirSync(teamDir, { recursive: true, mode: 448 }); + fs8.writeFileSync(path7.join(teamDir, "socket.path"), socketPath + "\n", { mode: 384 }); +} +function removeSocketRegistryIf(teamDir, socketPath) { + const file = path7.join(teamDir, "socket.path"); + try { + const current = fs8.readFileSync(file, "utf8").trim(); + if (current !== socketPath) return; + } catch { + return; + } + try { + fs8.unlinkSync(file); + } catch { + } +} + +// src/coord/store-adapter.ts +var JournalTeamStore = class _JournalTeamStore { + constructor(journalInstance, ownedLock) { + this.journalInstance = journalInstance; + this.ownedLock = ownedLock; + this.journal = journalInstance; + } + journal; + cached; + unsubs = []; + /** 冷启动加载信息(host readyInfo 用;open 时捕获)。 */ + lastLoad = null; + /** 打开(含抢锁 + 冷启动重放 + O_APPEND 句柄)。 */ + static async open(dataRoot, teamId, opts = {}) { + const paths = teamPaths(dataRoot, teamId); + ensureTeamDir(paths); + let lock = opts.lock; + let owned = false; + if (lock === void 0) { + lock = new CoordinatorLock(paths.lockFile, paths.auditFile); + await lock.acquire({ waitMs: opts.lockWaitMs ?? 3e4 }); + owned = true; + } + const journal = TeamJournal.open(paths.teamDir, teamId, opts.journal); + const identity = writerId(); + const loaded = await journal.openWriter( + lock.info?.token === void 0 ? identity : `${identity}:${lock.info.token}` + ); + const store = new _JournalTeamStore(journal, owned ? lock : void 0); + store.lastLoad = { seq: loaded.seq, fromCheckpoint: loaded.fromCheckpoint }; + return store; + } + async append(event) { + const result = await this.journal.appendAndFlush(event); + this.cached = result.state; + return result; + } + state() { + if (this.cached === void 0) { + const cached2 = this.journal.cachedState; + if (cached2 === null) throw new Error("journal store not opened"); + this.cached = cached2; + } + return this.cached; + } + /** 已提交行号(= hello.stateRevision 的冻结语义:journal seq)。 */ + get committedSeq() { + return this.journal.committedSeq; + } + /** 〔D33〕原始事件行(含 ts):provisioning 对账宽限读事件年龄;只读全量回放,不持锁。 */ + async readEventLines() { + const lines = await this.journal.readAll(); + return lines.map((line) => ({ ts: line.ts, event: line.event })); + } + transact(op) { + return this.journal.transact(op); + } + onCommit(listener) { + const adapted = (_entry, state) => { + this.cached = state; + listener(0, state); + }; + const off = this.journal.onCommit(adapted); + this.unsubs.push(off); + return off; + } + /** 释放(自有锁则释放);失锁路径不得再发布需要当前所有权的 checkpoint。 */ + async close(opts = {}) { + for (const off of this.unsubs) off(); + this.unsubs.length = 0; + await this.journal.close(opts); + await this.ownedLock?.release(); + } +}; + +// src/coord/rpc.ts +import net from "node:net"; +import fs9 from "node:fs"; +import path8 from "node:path"; +import crypto3 from "node:crypto"; +var COORDINATOR_UNAVAILABLE_MESSAGE = "Agent Teams coordinator is unavailable (between coordinators); retry the request shortly"; +var SUN_PATH_LIMIT = 104; +var MAX_RPC_BUFFER_BYTES = 1 << 20; +function frameBudgetFor(maxMessageBytes) { + return Math.max(MAX_RPC_BUFFER_BYTES, maxMessageBytes * 4); +} +var RpcServer = class { + socketPath; + server = null; + socketIno = null; + /** 活连接(close 时主动断开,防幽灵客户端阻塞关停)。 */ + clients = /* @__PURE__ */ new Set(); + handlers = /* @__PURE__ */ new Map(); + maxFrameBytes; + token; + nextId = 0; + constructor(socketPath, opts = {}) { + if (socketPath.length > SUN_PATH_LIMIT) { + throw new Error( + `unix socket path too long for macOS (sun_path \u2248${SUN_PATH_LIMIT}B, got ${socketPath.length}B): ${socketPath} \u2014 use resolveSocketPath() to fall back to a short /tmp path` + ); + } + this.socketPath = socketPath; + this.maxFrameBytes = opts.maxFrameBytes ?? MAX_RPC_BUFFER_BYTES; + this.token = opts.token; + } + register(method, handler, opts = {}) { + this.handlers.set(method, { handler, timeoutMs: opts.timeoutMs }); + return this; + } + has(method) { + return this.handlers.has(method); + } + async listen(opts = {}) { + const callTimeoutMs = opts.callTimeoutMs ?? 1e4; + if (fs9.existsSync(this.socketPath)) { + const active = await probeActiveSocket(this.socketPath); + if (active) { + throw new Error( + `rpc socket already in use by an active coordinator: ${this.socketPath} (refusing to replace it)` + ); + } + try { + fs9.unlinkSync(this.socketPath); + } catch { + } + } + await new Promise((resolve, reject) => { + const server2 = net.createServer((socket) => { + this.clients.add(socket); + const inflight = /* @__PURE__ */ new Set(); + socket.once("close", () => { + this.clients.delete(socket); + for (const controller of inflight) controller.abort(); + inflight.clear(); + }); + socket.setEncoding("utf8"); + let buffer = ""; + socket.on("data", (chunk) => { + buffer += chunk; + if (Buffer.byteLength(buffer, "utf8") > this.maxFrameBytes) { + socket.destroy(); + return; + } + let nl; + while ((nl = buffer.indexOf("\n")) !== -1) { + const line = buffer.slice(0, nl); + buffer = buffer.slice(nl + 1); + if (line.trim().length === 0) continue; + let parsed; + try { + parsed = JSON.parse(line); + } catch { + socket.write(JSON.stringify({ id: -1, ok: false, error: { message: "invalid rpc frame" } }) + "\n"); + continue; + } + if (!this.authorized(parsed)) { + const id = typeof parsed?.id === "number" ? parsed.id : -1; + socket.write(JSON.stringify({ id, ok: false, error: { message: "unauthorized rpc frame" } }) + "\n"); + continue; + } + void this.dispatch(parsed, socket, callTimeoutMs, inflight); + } + }); + socket.on("error", () => socket.destroy()); + }); + server2.on("error", (err) => reject(err)); + server2.listen(this.socketPath, () => { + this.server = server2; + try { + fs9.chmodSync(this.socketPath, 384); + this.socketIno = fs9.statSync(this.socketPath).ino; + } catch (err) { + this.server = null; + try { + server2.close(); + } catch { + } + reject( + new Error( + `rpc socket hardening failed for ${this.socketPath}: ${err instanceof Error ? err.message : String(err)}` + ) + ); + return; + } + resolve(); + }); + }); + } + async close() { + const server2 = this.server; + if (server2 === null) return; + this.server = null; + const ino = this.socketIno; + this.socketIno = null; + for (const client of this.clients) { + try { + client.destroy(); + } catch { + } + } + this.clients.clear(); + let preserve = null; + if (ino !== null) { + try { + if (fs9.statSync(this.socketPath).ino !== ino) { + const quarantine = `${this.socketPath}.preserve-${process.pid}-${crypto3.randomBytes(4).toString("hex")}`; + fs9.renameSync(this.socketPath, quarantine); + preserve = { quarantine }; + } + } catch { + } + } + await new Promise((resolve) => server2.close(() => resolve())); + if (preserve !== null) { + try { + fs9.renameSync(preserve.quarantine, this.socketPath); + } catch (err) { + process.stderr.write( + JSON.stringify({ + ts: (/* @__PURE__ */ new Date()).toISOString(), + scope: "rpc", + msg: "failed to restore preserved socket path", + socketPath: this.socketPath, + quarantine: preserve.quarantine, + error: err instanceof Error ? err.message : String(err) + }) + "\n" + ); + } + } + } + authorized(req) { + if (this.token === void 0) return true; + const provided = typeof req?.token === "string" ? req.token : ""; + const a = Buffer.from(provided); + const b = Buffer.from(this.token); + return a.length === b.length && crypto3.timingSafeEqual(a, b); + } + async dispatch(req, socket, callTimeoutMs, inflight) { + const respond = (res) => { + if (!socket.destroyed) socket.write(JSON.stringify(res) + "\n"); + }; + const id = typeof req?.id === "number" ? req.id : -1; + const registered = this.handlers.get(req?.method); + if (registered === void 0) { + respond({ id, ok: false, error: { message: `unknown rpc method: ${String(req?.method)}` } }); + return; + } + const timeoutMs = registered.timeoutMs ?? callTimeoutMs; + const abort = new AbortController(); + inflight.add(abort); + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + respond({ id, ok: false, error: { message: `rpc method ${req.method} timed out after ${timeoutMs}ms` } }); + abort.abort(); + }, timeoutMs); + try { + const result = await registered.handler(req.params, { + socketPath: this.socketPath, + signal: abort.signal + }); + if (!settled) { + settled = true; + respond({ id, ok: true, result }); + } + } catch (err) { + if (settled) return; + if (isTeamError(err)) { + respond({ + id, + ok: false, + error: { message: err.message, code: err.code, serialized: serializeTeamError(err) } + }); + } else { + respond({ + id, + ok: false, + error: { message: err instanceof Error ? err.message : String(err), name: err instanceof Error ? err.name : void 0 } + }); + } + } finally { + clearTimeout(timer); + inflight.delete(abort); + } + } +}; +var RpcClient = class _RpcClient { + constructor(socket, token = void 0, nextId = 1, pending = /* @__PURE__ */ new Map(), maxFrameBytes = MAX_RPC_BUFFER_BYTES) { + this.socket = socket; + this.token = token; + this.nextId = nextId; + this.pending = pending; + this.maxFrameBytes = maxFrameBytes; + } + maxFrameBytes; + static async connect(socketPath, opts = {}) { + const timeoutMs = opts.timeoutMs ?? 3e3; + const socket = await new Promise((resolve, reject) => { + const s = net.connect(socketPath, () => resolve(s)); + s.setEncoding("utf8"); + const timer = setTimeout(() => { + s.destroy(); + reject(new Error(`rpc connect timeout after ${timeoutMs}ms: ${socketPath}`)); + }, timeoutMs); + s.once("error", (err) => { + clearTimeout(timer); + reject(err); + }); + resolveSocketOnConnect(s, () => clearTimeout(timer)); + }); + const client = new _RpcClient(socket, opts.token, 1, /* @__PURE__ */ new Map(), opts.maxFrameBytes); + socket.on("data", (chunk) => client.onData(chunk)); + socket.on("close", () => client.failAll(new Error("rpc connection closed"))); + socket.on("error", (err) => client.failAll(err)); + return client; + } + async call(method, params, opts = {}) { + const id = this.nextId++; + const timeoutMs = opts.timeoutMs ?? 15e3; + if (opts.signal?.aborted) { + return Promise.reject( + new TeamError("TEAM_WAIT_ABORTED", `wait_agent aborted: ${abortReasonText(opts.signal.reason)}`) + ); + } + const payload = JSON.stringify({ id, method, params, ...this.token !== void 0 ? { token: this.token } : {} }) + "\n"; + return new Promise((resolve, reject) => { + let settled = false; + let timer; + const finish = (fn) => { + if (settled) return; + settled = true; + clearTimeout(timer); + opts.signal?.removeEventListener("abort", onAbort); + this.pending.delete(id); + fn(); + }; + const onAbort = () => { + finish( + () => reject(new TeamError("TEAM_WAIT_ABORTED", `wait_agent aborted: ${abortReasonText(opts.signal?.reason)}`)) + ); + this.socket.destroy(); + }; + timer = setTimeout(() => { + finish(() => reject(new Error(`rpc call ${method} timed out after ${timeoutMs}ms`))); + }, timeoutMs); + this.pending.set(id, { + resolve: (v) => finish(() => resolve(v)), + reject: (e) => finish(() => reject(e)) + }); + opts.signal?.addEventListener("abort", onAbort, { once: true }); + this.socket.write(payload, (err) => { + if (err) finish(() => reject(err)); + }); + }); + } + close() { + this.socket.destroy(); + } + onData(chunk) { + this.buffer += chunk; + if (Buffer.byteLength(this.buffer, "utf8") > this.maxFrameBytes) { + this.failAll(new Error(`rpc response frame exceeds ${this.maxFrameBytes} bytes`)); + this.socket.destroy(); + return; + } + let nl; + while ((nl = this.buffer.indexOf("\n")) !== -1) { + const line = this.buffer.slice(0, nl); + this.buffer = this.buffer.slice(nl + 1); + if (line.trim().length === 0) continue; + try { + this.onResponse(JSON.parse(line)); + } catch { + this.failAll(new Error("invalid rpc response frame")); + } + } + } + buffer = ""; + onResponse(res) { + const entry = this.pending.get(res.id); + if (entry === void 0) return; + this.pending.delete(res.id); + if (res.ok) { + entry.resolve(res.result); + } else if (res.error?.code !== void 0) { + entry.reject(new TeamError(res.error.code, res.error.message)); + } else { + const err = new Error(res.error?.message ?? "rpc error"); + if (res.error?.name) err.name = res.error.name; + entry.reject(err); + } + } + failAll(err) { + for (const [, entry] of this.pending) entry.reject(err); + this.pending.clear(); + } +}; +function resolveSocketOnConnect(socket, onConnected) { + socket.once("connect", onConnected); +} +function probeActiveSocket(socketPath, timeoutMs = 500) { + return new Promise((resolve) => { + const socket = net.connect(socketPath); + let settled = false; + const finish = (active) => { + if (settled) return; + settled = true; + socket.destroy(); + resolve(active); + }; + const timer = setTimeout(() => finish(false), timeoutMs); + timer.unref?.(); + socket.once("connect", () => { + clearTimeout(timer); + finish(true); + }); + socket.once("error", () => { + clearTimeout(timer); + finish(false); + }); + }); +} +function rpcTokenPath(teamDir) { + return path8.join(teamDir, "rpc.token"); +} +function readRpcToken(teamDir) { + try { + const token = fs9.readFileSync(rpcTokenPath(teamDir), "utf8").trim(); + return token.length > 0 ? token : void 0; + } catch { + return void 0; + } +} +function writeRpcToken(teamDir, token) { + fs9.mkdirSync(teamDir, { recursive: true, mode: 448 }); + fs9.writeFileSync(rpcTokenPath(teamDir), token + "\n", { mode: 384 }); +} +function newRpcToken() { + return crypto3.randomBytes(24).toString("hex"); +} +function coordinatorUnavailableError(detail) { + return new TeamError("TEAM_DISPOSED", COORDINATOR_UNAVAILABLE_MESSAGE, { cause: detail }); +} +function abortReasonText(reason) { + if (reason instanceof Error) return reason.message; + if (reason === void 0 || reason === null) return "aborted"; + return String(reason); +} +async function callCoordinator(teamDir, teamId, method, params, opts = {}) { + const socketPath = discoverSocketPath(teamDir); + const token = readRpcToken(teamDir); + const client = await RpcClient.connect(socketPath, { + timeoutMs: opts.connectTimeoutMs ?? 1e3, + ...token !== void 0 ? { token } : {} + }).catch((err) => { + throw coordinatorUnavailableError(`socket ${socketPath}: ${err.code ?? err.message}`); + }); + try { + return await client.call(method, params, { + timeoutMs: opts.timeoutMs, + ...opts.signal !== void 0 ? { signal: opts.signal } : {} + }); + } finally { + client.close(); + } +} + +// src/provider/model-selection.ts +var DEFAULT_REASONING_LEVEL = "max"; +function parseModelSelection(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0; + const record2 = value; + const providerId = nonEmptyString(record2.providerId); + const modelId = nonEmptyString(record2.modelId); + if (providerId === void 0 || modelId === void 0) return void 0; + const options = record2.options; + if (options !== void 0 && (typeof options !== "object" || options === null || Array.isArray(options))) { + return void 0; + } + let reasoningLevel; + const rawLevel = options !== void 0 ? options.reasoningLevel : record2.reasoningLevel; + if (rawLevel !== void 0) { + reasoningLevel = nonEmptyString(rawLevel); + if (reasoningLevel === void 0) return void 0; + } + return { providerId, modelId, ...reasoningLevel !== void 0 ? { reasoningLevel } : {} }; +} +function nonEmptyString(value) { + if (typeof value !== "string") return void 0; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : void 0; +} + +// src/domain/ports.ts +var realClock = { + now: () => Date.now(), + sleep: (ms, signal) => new Promise((resolve) => { + if (signal?.aborted) { + resolve(); + return; + } + const onAbort = () => { + clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + resolve(); + }; + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + signal?.addEventListener("abort", onAbort, { once: true }); + }) +}; +function errorMessage(err) { + const message = err instanceof Error ? err.message : String(err); + return message.split("\n")[0] ?? message; +} + +// src/domain/activity.ts +function isValidTimeout(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 1e4 && value <= 36e5; +} +var NO_PROGRESS_REASON = "no-active-peer"; +var NO_PROGRESS_MESSAGE = "No other Team member is running or provisioning. wait_agent cannot make progress or wake inactive teammates. Re-list with list_agents and team_task_list, then use send_message to wake each required inactive teammate before waiting again."; +function noProgressResult() { + return { timedOut: false, noProgress: { reason: NO_PROGRESS_REASON, message: NO_PROGRESS_MESSAGE } }; +} +var TeamActivity = class { + constructor(deps) { + this.deps = deps; + this.clock = deps.clock ?? realClock; + } + waiters = /* @__PURE__ */ new Set(); + closed = false; + clock; + unsubscribeCommit; + /** 接线:Team 日志提交边(由 runtime/装配调用;每提交唤醒全部已注册等待者一次)。 */ + bindCommitEdge() { + this.unsubscribeCommit?.(); + this.unsubscribeCommit = this.deps.store.onCommit(() => this.wakeAll()); + return () => this.unsubscribeCommit?.(); + } + /** 接线:成员状态变化边(roster.onMemberStatus → 此处)。 */ + notifyMemberStatus() { + this.wakeAll(); + } + /** 处置:唤醒全部等待者并关闭准入(新等待立即返回 { timedOut:false })。 */ + closeAll() { + this.closed = true; + this.wakeAll(); + } + /** §8 waitForChange。 */ + async waitForChange(callerId, timeoutMs = 3e4, signal) { + if (!isValidTimeout(timeoutMs)) { + throw new TeamError( + "TEAM_INVALID_TIMEOUT", + "timeoutMs must be an integer from 10000 through 3600000" + ); + } + signal?.throwIfAborted(); + if (this.closed) return { timedOut: false }; + requireMembership(() => this.loadState(), callerId); + return new Promise((resolve, reject) => { + const sleepAbort = new AbortController(); + const waiter = { + wake: () => { + cleanup(); + resolve({ timedOut: false }); + } + }; + const onAbort = () => { + cleanup(); + const reason = signal?.reason; + if (reason instanceof Error) reject(reason); + else + reject( + new TeamError("TEAM_WAIT_ABORTED", `wait_agent aborted: ${errorMessage(reason)}`) + ); + }; + const cleanup = () => { + if (settled) return; + this.waiters.delete(waiter); + settled = true; + signal?.removeEventListener("abort", onAbort); + sleepAbort.abort(); + }; + let settled = false; + this.waiters.add(waiter); + signal?.addEventListener("abort", onAbort, { once: true }); + void this.clock.sleep(timeoutMs, sleepAbort.signal).then(() => { + if (settled) return; + cleanup(); + resolve({ timedOut: true }); + }); + }); + } + wakeAll() { + const current = [...this.waiters]; + this.waiters.clear(); + for (const waiter of current) waiter.wake(); + } + loadState() { + const state = this.deps.store.state(); + if (state.failure !== void 0) throw new Error(state.failure); + return state; + } +}; + +// src/provider/framing.ts +function renderFramed(framedJson) { + const blocks = JSON.parse(framedJson); + if (!Array.isArray(blocks) || blocks.length === 0) { + throw new Error("framed message must be a non-empty JSON array of content blocks"); + } + const header = blocks[0]; + if (header.type !== "text" || typeof header.text !== "string") { + throw new Error("framed message first block must be the text header"); + } + const m = header.text.match(/^Team message from (.+):$/); + if (m === null) { + throw new Error(`framed message header mismatch: ${JSON.stringify(header.text)}`); + } + const lines = [header.text]; + for (const block of blocks.slice(1)) { + if (block.type === "text" && typeof block.text === "string") { + lines.push(block.text); + } else { + lines.push(JSON.stringify(block)); + } + } + return { messageId: "", senderName: m[1], text: lines.join("\n") }; +} +function renderFramedBatch(items) { + const rendered = items.map((item) => ({ ...renderFramed(item.framedJson), messageId: item.messageId })); + return { promptText: rendered.map((r) => r.text).join("\n\n"), rendered }; +} + +// src/hooks/inbox.ts +function pendingLeadMessages(teamDir, state) { + if (state.failure !== void 0) return []; + const teamId = state.id; + const delivered = new Set(state.delivered); + const receipted = receiptMessageIds(memberPaths(teamDir, teamId)); + const pending = []; + for (const message of state.messages) { + if (message.targetId !== teamId || delivered.has(message.id) || receipted.has(message.id)) continue; + const framed = [ + { type: "text", text: `Team message from ${message.senderName}:` }, + ...message.content + ]; + pending.push({ + messageId: message.id, + senderName: message.senderName, + text: renderFramed(JSON.stringify(framed)).text + }); + } + return pending; +} +function writeReceipts(dataRoot, teamId, messageIds, channel) { + const paths = memberPaths(teamPaths(dataRoot, teamId).teamDir, teamId); + for (const messageId of messageIds) { + appendReceipt(paths, { messageId, channel, ts: (/* @__PURE__ */ new Date()).toISOString() }); + } +} + +// src/coord/methods.ts +var TASK_ACTIONS = [ + "claim", + "release", + "edit", + "set_dependencies", + "complete", + "reopen", + "reassign", + "delete" +]; +var WAIT_AGENT_GRACE_MS = 5e3; +var METHOD_TIMEOUT_OVERRIDES = { + "member.spawn": 18e4, + "message.send": 3e4 +}; +function methodTimeoutMs(method) { + return METHOD_TIMEOUT_OVERRIDES[method]; +} +function buildTeamMethodTable(deps) { + const { runtime, store } = deps; + const { teamDir } = teamPaths(deps.dataRoot, deps.teamId); + const table = /* @__PURE__ */ new Map(); + table.set("coordinator.hello", (raw) => { + const p = asParams(raw, "coordinator.hello"); + assertTeamTarget(p, "coordinator.hello", deps); + return { + coordinatorBootId: deps.coordinatorBootId, + stateRevision: store.committedSeq + }; + }); + table.set("member.claim", (raw) => { + const p = asParams(raw, "member.claim"); + assertTeamTarget(p, "member.claim", deps); + const sessionId = requireSessionId(p, "member.claim"); + const membership = requireMembership(membershipStateLoader(store), sessionId); + return { role: membership.role }; + }); + const memberSpawn = async (raw, ctx) => { + const p = asParams(raw, "member.spawn"); + assertTeamTarget(p, "member.spawn", deps); + const sessionId = requireSessionId(p, "member.spawn"); + const context = optionalString(p, "context", "member.spawn", { enum: ["fresh", "fork"] }); + return runtime.roster.spawnTeammate(sessionId, { + // 空串下沉到域层:name → TEAM_INVALID_MEMBER_NAME;description → must be non-empty。 + name: requireString(p, "name", "member.spawn", { allowEmpty: true }), + description: requireString(p, "description", "member.spawn", { allowEmpty: true }), + prompt: requireString(p, "prompt", "member.spawn", { allowEmpty: true }), + ...typeof p.requestId === "string" && p.requestId.length > 0 ? { requestId: p.requestId } : {}, + ...ctx?.signal !== void 0 ? { signal: ctx.signal, ownershipSignal: ctx.signal } : {}, + ...context !== void 0 ? { context } : {} + }); + }; + memberSpawn.timeoutMs = 18e4; + table.set("member.spawn", memberSpawn); + table.set("member.interrupt", async (raw) => { + const p = asParams(raw, "member.interrupt"); + assertTeamTarget(p, "member.interrupt", deps); + const sessionId = requireSessionId(p, "member.interrupt"); + const name = requireString(p, "name", "member.interrupt", { allowEmpty: true }); + return runtime.roster.interrupt(sessionId, name); + }); + const messageSend = async (raw) => { + const p = asParams(raw, "message.send"); + assertTeamTarget(p, "message.send", deps); + const sessionId = requireSessionId(p, "message.send"); + const targetName = requireString(p, "targetName", "message.send", { allowEmpty: true }); + if (!Array.isArray(p.content)) { + throw new TeamError("TEAM_INVALID_ARGUMENT", 'message.send param "content" must be an array of content blocks'); + } + return runtime.mailbox.send(sessionId, { target: targetName, content: p.content }); + }; + messageSend.timeoutMs = 3e4; + table.set("message.send", messageSend); + table.set("mailbox.ack", async (raw) => { + const p = asParams(raw, "mailbox.ack"); + assertTeamTarget(p, "mailbox.ack", deps); + const sessionId = requireSessionId(p, "mailbox.ack"); + if (!Array.isArray(p.messageIds) || p.messageIds.some((id) => typeof id !== "string")) { + throw new TeamError("TEAM_INVALID_ARGUMENT", 'mailbox.ack param "messageIds" must be an array of strings'); + } + const messageIds = p.messageIds; + const targetId = typeof p.targetId === "string" && p.targetId.length > 0 ? p.targetId : sessionId; + for (const messageId of messageIds) { + await runtime.mailbox.observeDelivery(targetId, messageId); + } + return { acknowledged: messageIds.length }; + }); + table.set("task.create", async (raw) => { + const p = asParams(raw, "task.create"); + assertTeamTarget(p, "task.create", deps); + const sessionId = requireSessionId(p, "task.create"); + const blockedBy = optionalStringArray(p, "blockedBy", "task.create"); + const writeScopes2 = optionalStringArray(p, "writeScopes", "task.create"); + return runtime.taskboard.create(sessionId, { + subject: requireString(p, "subject", "task.create", { allowEmpty: true }), + description: requireString(p, "description", "task.create", { allowEmpty: true }), + ...blockedBy !== void 0 ? { blockedBy } : {}, + ...writeScopes2 !== void 0 ? { writeScopes: writeScopes2 } : {} + }); + }); + table.set("task.update", async (raw) => { + const p = asParams(raw, "task.update"); + assertTeamTarget(p, "task.update", deps); + const sessionId = requireSessionId(p, "task.update"); + const action = requireString(p, "action", "task.update"); + if (!TASK_ACTIONS.includes(action)) { + throw new TeamError( + "TEAM_INVALID_ARGUMENT", + `task.update param "action" must be one of ${TASK_ACTIONS.join(", ")}` + ); + } + const expectedRevision = p.expectedRevision; + if (typeof expectedRevision !== "number" || !Number.isSafeInteger(expectedRevision)) { + throw new TeamError("TEAM_INVALID_ARGUMENT", 'task.update param "expectedRevision" must be a safe integer'); + } + const subject = optionalString(p, "subject", "task.update", { allowEmpty: true }); + const description = optionalString(p, "description", "task.update", { allowEmpty: true }); + const blockedBy = optionalStringArray(p, "blockedBy", "task.update"); + const writeScopes2 = optionalStringArray(p, "writeScopes", "task.update"); + const owner = optionalString(p, "owner", "task.update", { allowEmpty: true }); + return runtime.taskboard.update(sessionId, { + taskId: requireString(p, "taskId", "task.update", { allowEmpty: true }), + expectedRevision, + action, + ...subject !== void 0 ? { subject } : {}, + ...description !== void 0 ? { description } : {}, + ...blockedBy !== void 0 ? { blockedBy } : {}, + ...writeScopes2 !== void 0 ? { writeScopes: writeScopes2 } : {}, + ...owner !== void 0 ? { owner } : {} + }); + }); + table.set("task.list", (raw) => { + const p = asParams(raw, "task.list"); + assertTeamTarget(p, "task.list", deps); + const sessionId = requireSessionId(p, "task.list"); + const status = optionalString(p, "status", "task.list"); + const owner = optionalString(p, "owner", "task.list"); + return runtime.taskboard.list(sessionId, { + ...status !== void 0 ? { status } : {}, + ...owner !== void 0 ? { owner } : {}, + ...typeof p.ready === "boolean" ? { ready: p.ready } : {}, + ...typeof p.cursor === "number" ? { cursor: p.cursor } : {}, + ...typeof p.limit === "number" ? { limit: p.limit } : {} + }); + }); + table.set("task.get", (raw) => { + const p = asParams(raw, "task.get"); + assertTeamTarget(p, "task.get", deps); + const sessionId = requireSessionId(p, "task.get"); + return runtime.taskboard.get(sessionId, requireString(p, "taskId", "task.get", { allowEmpty: true })); + }); + table.set("board.read", (raw) => { + const p = asParams(raw, "board.read"); + assertTeamTarget(p, "board.read", deps); + const sessionId = typeof p.session_id === "string" ? p.session_id : void 0; + if (sessionId !== void 0) { + requireMembership(membershipStateLoader(store), sessionId); + } + return { revision: store.committedSeq, view: teamProjectionView(store.state()) }; + }); + const waitAgent = async (raw, ctx) => { + const p = asParams(raw, "wait.agent"); + assertTeamTarget(p, "wait.agent", deps); + const sessionId = requireSessionId(p, "wait.agent"); + const timeoutMs = typeof p.timeoutMs === "number" ? p.timeoutMs : 3e4; + if (!isValidTimeout(timeoutMs) || runtime.lifecycle.status !== "open") { + return runtime.activity.waitForChange(sessionId, timeoutMs, ctx?.signal); + } + ctx?.signal?.throwIfAborted(); + runtime.lifecycle.runtimeSignal().throwIfAborted(); + const membership = requireMembership(membershipStateLoader(store), sessionId); + const receiveMessages = () => { + ctx?.signal?.throwIfAborted(); + runtime.lifecycle.runtimeSignal().throwIfAborted(); + if (sessionId !== deps.teamId) return { messages: [] }; + const pending = pendingLeadMessages(teamDir, store.state()); + const messages = []; + const messageIds = []; + const receiptWarning = "\u6536\u4EF6\u56DE\u6267\u6301\u4E45\u5316\u5931\u8D25\uFF1B\u672C\u6279\u6B63\u6587\u5DF2\u8FD4\u56DE\uFF0C\u672A\u786E\u8BA4\u6D88\u606F\u53EF\u80FD\u91CD\u590D\u3002"; + let bytes = Buffer.byteLength(JSON.stringify({ + id: Number.MAX_SAFE_INTEGER, + ok: true, + result: { timedOut: false, messages: [], receiptWarning } + })) + 1; + for (const message of pending) { + const size = Buffer.byteLength(JSON.stringify(message.text)) + (messages.length > 0 ? 1 : 0); + if (bytes + size > MAX_RPC_BUFFER_BYTES) { + if (messages.length === 0) throw new Error("\u5355\u6761\u6210\u5458\u6D88\u606F\u8D85\u8FC7\u6536\u4EF6\u7BB1\u54CD\u5E94\u4E0A\u9650\uFF0C\u6D88\u606F\u4FDD\u6301\u5F85\u6536\uFF1B\u8BF7\u67E5\u770B\u6210\u5458\u4F1A\u8BDD\u83B7\u53D6\u5B8C\u6574\u7ED3\u679C\u3002"); + break; + } + bytes += size; + messages.push(message.text); + messageIds.push(message.messageId); + } + try { + writeReceipts(deps.dataRoot, deps.teamId, messageIds, "wait_agent"); + } catch (err) { + try { + deps.warn?.(`agent-team inbox receipt failed: ${err instanceof Error ? err.message : String(err)}`); + } catch { + } + return { messages, receiptWarning }; + } + return { messages }; + }; + const inbox = receiveMessages(); + if (inbox.messages.length > 0) return { timedOut: false, ...inbox }; + const rows = runtime.roster.listMembers(sessionId).members; + if (!runtime.roster.hasPendingAutomaticProgress(sessionId)) { + const stopped = rows.find((row) => row.status === "provisioning"); + if (stopped !== void 0) { + const message = `\u6210\u5458 ${stopped.target} \u5DF2\u505C\u6B62\u81EA\u52A8\u786E\u8BA4\uFF0C\u9700\u8981 Lead \u63A5\u7BA1\uFF1B\u65E7 turn \u4ECD\u53EF\u80FD\u6267\u884C\uFF0C\u4E0D\u5F97\u91CD\u590D\u542F\u52A8\u3002`; + return { ...noProgressResult(), noProgress: { reason: "no-active-peer", message }, content: [{ type: "text", text: message }] }; + } + return noProgressResult(); + } + const self = membership.role === "lead" ? "lead" : membership.name; + if (!rows.some((row) => row.target !== self && (row.status === "running" || row.status === "provisioning"))) { + return noProgressResult(); + } + const result = await runtime.activity.waitForChange(sessionId, timeoutMs, ctx?.signal); + if (runtime.lifecycle.status !== "open") return result; + const received = receiveMessages(); + return received.messages.length > 0 ? { timedOut: false, ...received } : result; + }; + waitAgent.timeoutMs = 36e5 + WAIT_AGENT_GRACE_MS; + table.set("wait.agent", waitAgent); + table.set("admin.reconcile", (raw) => { + const p = asParams(raw, "admin.reconcile"); + assertTeamTarget(p, "admin.reconcile", deps); + return runtime.roster.reconcileProvisioning(); + }); + return table; +} +function registerTeamMethods(server2, table) { + for (const [method, handler] of table) { + server2.register( + method, + (params, ctx) => handler(params, ctx), + handler.timeoutMs !== void 0 ? { timeoutMs: handler.timeoutMs } : {} + ); + } + return server2; +} +async function invokeTeamMethod(table, method, params, ctx) { + const handler = table.get(method); + if (handler === void 0) { + throw new Error(`unknown rpc method: ${method}`); + } + return handler(params, ctx); +} +function membershipStateLoader(store) { + return () => { + const state = store.state(); + if (state.failure !== void 0) throw projectionFailureError(state.failure); + return state; + }; +} +function asParams(raw, method) { + if (raw === void 0 || raw === null) return {}; + if (typeof raw !== "object" || Array.isArray(raw)) { + throw new TeamError("TEAM_INVALID_ARGUMENT", `${method} params must be an object`); + } + return raw; +} +function assertTeamTarget(p, method, deps) { + if (p.teamId !== void 0 && p.teamId !== deps.teamId) { + throw new Error( + `rpc method ${method} targets team ${JSON.stringify(p.teamId)} but this coordinator serves ${JSON.stringify(deps.teamId)}` + ); + } +} +function requireSessionId(p, method) { + const v = p.session_id; + if (typeof v !== "string" || v.length === 0) { + throw new TeamError("TEAM_INVALID_ARGUMENT", `${method} param "session_id" is required`); + } + return v; +} +function requireString(p, key, method, opts = {}) { + const v = p[key]; + if (typeof v !== "string" || !opts.allowEmpty && v.length === 0) { + throw new TeamError( + "TEAM_INVALID_ARGUMENT", + `${method} param "${key}" must be a${opts.allowEmpty ? " string" : " non-empty string"}` + ); + } + return v; +} +function optionalString(p, key, method, opts = {}) { + const v = p[key]; + if (v === void 0) return void 0; + if (typeof v !== "string" || !opts.allowEmpty && v.length === 0) { + throw new TeamError( + "TEAM_INVALID_ARGUMENT", + `${method} param "${key}" must be a${opts.allowEmpty ? " string" : " non-empty string"}` + ); + } + if (opts.enum !== void 0 && !opts.enum.includes(v)) { + throw new TeamError("TEAM_INVALID_ARGUMENT", `${method} param "${key}" must be one of ${opts.enum.join(", ")}`); + } + return v; +} +function optionalStringArray(p, key, method) { + const v = p[key]; + if (v === void 0) return void 0; + if (!Array.isArray(v) || v.some((item) => typeof item !== "string")) { + throw new TeamError("TEAM_INVALID_ARGUMENT", `${method} param "${key}" must be an array of strings`); + } + return v; +} + +// src/domain/lifecycle.ts +var TeamLifecycle = class { + constructor(deps) { + this.deps = deps; + } + phase = "open"; + abort = new AbortController(); + inflight = /* @__PURE__ */ new Set(); + disposeRun; + get status() { + return this.phase; + } + requireOpen() { + if (this.phase !== "open") { + throw new TeamError("TEAM_DISPOSED", "Agent Teams service is disposing"); + } + } + runtimeSignal() { + return this.abort.signal; + } + track(p) { + this.inflight.add(p); + void p.finally(() => { + this.inflight.delete(p); + }).catch(() => void 0); + return p; + } + /** 代次撤销只取消当前等待,不进入需要所有权的 drain/turn 清理。 */ + revokeGeneration(reason) { + this.abort.abort(reason ?? new TeamError("TEAM_DISPOSED", "coordinator generation revoked")); + } + /** dispose(reason):D9 抽象触发;幂等(重复调用等首次结果)。 */ + dispose(reason) { + this.disposeRun ??= this.runDispose(); + return this.disposeRun; + } + async runDispose() { + const failures = []; + this.phase = "disposing"; + this.abort.abort(new TeamError("TEAM_DISPOSED", "Agent Teams service disposed")); + this.deps.closeWaiters?.(); + const clock = this.deps.clock ?? defaultClock; + const settle = Promise.allSettled([...this.inflight]); + let settled = []; + const timedOut = await Promise.race([ + settle.then((results) => { + settled = results; + return false; + }), + clock.sleep(this.deps.disposalTimeoutMs).then(() => true) + ]); + for (const entry of settled) { + if (entry.status === "rejected" && !isCancellation(entry.reason)) failures.push(entry.reason); + } + if (timedOut) { + failures.push( + new TeamError( + "TEAM_DISPOSAL_TIMEOUT", + `Agent Teams runtime disposal exceeded ${this.deps.disposalTimeoutMs}ms` + ) + ); + } + try { + await this.deps.drainer({ timeoutMs: this.deps.disposalTimeoutMs }); + } catch (err) { + if (!isCancellation(err)) failures.push(err); + } + this.phase = "closed"; + if (failures.length > 0) { + throw new AggregateError(failures, "Agent Teams runtime disposal failed"); + } + } +}; +var defaultClock = { + now: () => Date.now(), + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) +}; +function isCancellation(err) { + let current = err; + for (let depth = 0; depth < 8 && current !== void 0 && current !== null; depth++) { + if (isTeamError(current) && current.code === "TEAM_DISPOSED") return true; + if (current instanceof AggregateError && current.errors.length > 0) { + if (current.errors.every((e) => isCancellation(e))) return true; + } + current = current.cause; + } + return false; +} + +// src/domain/validation.ts +function requiredText(field, value, maxLen) { + if (typeof value !== "string") { + throw new TeamError("TEAM_INVALID_ARGUMENT", `${field} must be non-empty`, { cause: { field } }); + } + const trimmed = value.trim(); + if (trimmed.length === 0) { + throw new TeamError("TEAM_INVALID_ARGUMENT", `${field} must be non-empty`, { cause: { field } }); + } + if (trimmed.length > maxLen) { + throw new TeamError("TEAM_INVALID_ARGUMENT", `${field} exceeds ${maxLen} characters`, { + cause: { field, length: trimmed.length } + }); + } + return trimmed; +} +function writeScope(scope) { + if (typeof scope !== "string") { + throw invalidWriteScope(scope); + } + let s = scope.replace(/\\/g, "/"); + while (s.startsWith("./")) s = s.slice(2); + while (s.endsWith("/")) s = s.slice(0, -1); + if (s.length === 0) throw invalidWriteScope(scope); + if (s.startsWith("/")) throw invalidWriteScope(scope); + if (/^[a-z]:/i.test(s)) throw invalidWriteScope(scope); + for (const segment of s.split("/")) { + if (segment.length === 0 || segment === "." || segment === "..") throw invalidWriteScope(scope); + } + return s; +} +function writeScopes(list) { + if (!Array.isArray(list)) { + throw new TeamError("TEAM_INVALID_ARGUMENT", "write_scopes must be an array"); + } + const seen = /* @__PURE__ */ new Set(); + const out = []; + for (const scope of list) { + const normalized = writeScope(scope); + if (!seen.has(normalized)) { + seen.add(normalized); + out.push(normalized); + } + } + return out; +} +function invalidWriteScope(scope) { + return new TeamError( + "TEAM_INVALID_WRITE_SCOPE", + `invalid workspace-relative write scope ${JSON.stringify(scope)}`, + { cause: { scope } } + ); +} + +// src/provider/model-inheritance.ts +var ModelInheritanceError = class extends Error { + constructor(message, selection) { + super(message); + this.selection = selection; + this.name = "ModelInheritanceError"; + } +}; +var ModelSyncSuppressedError = class extends ModelInheritanceError { + constructor(message, selection) { + super(message, selection); + this.name = "ModelSyncSuppressedError"; + } +}; +function providerHasModelPreflight(provider) { + return typeof provider.preflightMemberModel === "function"; +} +function selectionSignature(selection) { + return `${selection.providerId}$${selection.modelId}$${selection.reasoningLevel ?? ""}`; +} +function classifyApplyFailure(reason) { + return /^Command failed:|timeout|did not become ready|timed out|spawn|exited|ENOENT|EACCES|ECONNREFUSED|EPIPE|socket hang up|client (is )?closed/i.test( + reason + ) ? "transient" : "deterministic"; +} +function classifySelectionFailure(message) { + return /无法确定 Lead 当前模型/.test(message) ? "transient" : "deterministic"; +} + +// src/domain/roster.ts +var NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; +var PROVISIONING_GRACE_MS = 6e4; +var PROVISIONING_RECHECK_MS = 1e4; +var TeamRoster = class { + constructor(deps) { + this.deps = deps; + } + statusListeners = /* @__PURE__ */ new Set(); + /** 〔D33〕defer 复核定时器(成员 id → timer;一次性、unref)。 */ + recheckTimers = /* @__PURE__ */ new Map(); + recoveryStopped = /* @__PURE__ */ new Set(); + recoveryDone; + /** 仅由宿主在完整意图/轮次恢复后启动;构造对象不得提前判 provisioning 失败。 */ + startRecovery() { + this.recoveryDone ??= this.reconcileProvisioning().then( + () => { + if (this.deps.lifecycle.runtimeSignal().aborted) return; + for (const member of this.loadState().members) { + if (member.phase === "provisioning" && !this.recoveryStopped.has(member.id)) { + this.scheduleProvisioningRecheck(member.id); + } + } + }, + () => void 0 + ); + return this.recoveryDone; + } + cancelPendingRecovery() { + for (const timer of this.recheckTimers.values()) clearTimeout(timer); + this.recheckTimers.clear(); + this.recoveryStopped.clear(); + } + /** 成员状态变化边(Activity 唤醒源之二;settle/interrupt 后触发)。 */ + onMemberStatus(listener) { + this.statusListeners.add(listener); + return () => this.statusListeners.delete(listener); + } + /** 外部状态变化通知(stage-4:provider 轮次边界 → Activity 唤醒;F13 ≤1s 路径)。 */ + notifyStatusChanged() { + this.notifyStatus(); + } + /** C5 服务层落点:投影 failure → 一切调用 TEAM_NOT_MEMBER。 */ + loadState() { + const state = this.deps.store.state(); + if (state.failure !== void 0) throw new Error(state.failure); + return state; + } + requireMember(callerId) { + const membership = requireMembership(() => { + const state = this.loadState(); + if (state.failure !== void 0) throw new Error(state.failure); + return state; + }, callerId); + return { state: this.loadState(), name: membership.name }; + } + // ---------------------------------------------------------------- spawn(§5.3) + async spawnTeammate(callerId, args) { + return this.deps.lifecycle.track(this.spawnInner(callerId, args)); + } + async spawnInner(callerId, args) { + const { state } = this.requireMember(callerId); + this.deps.lifecycle.requireOpen(); + if (callerId !== state.id) { + throw new TeamError("TEAM_LEAD_REQUIRED", "only the Team Lead can create teammates"); + } + const name = args.name; + if (typeof name !== "string" || name.length > 64 || name === "lead" || !NAME_PATTERN.test(name)) { + throw new TeamError( + "TEAM_INVALID_MEMBER_NAME", + 'teammate name must be lower-kebab-case, at most 64 characters, and not "lead"' + ); + } + const description = requiredText("description", args.description, 200); + const providers = this.deps.providers ?? { fresh: "spawn", fork: "fork" }; + const context = args.context ?? "fresh"; + const providerName = requiredText("provider", context === "fork" ? providers.fork : providers.fresh, 200); + const childId = (this.deps.newId ?? defaultNewId)(); + const requestId = args.requestId ?? defaultNewId(); + await this.deps.store.transact(async () => { + const fresh = this.loadState(); + if (fresh.members.some((m) => m.name === name)) { + throw new TeamError("TEAM_MEMBER_NAME_TAKEN", `teammate name "${name}" was already used in this Team`); + } + if (fresh.members.length >= this.deps.limits.maxMembers) { + throw new TeamError("TEAM_MEMBER_LIMIT", `Team member limit ${this.deps.limits.maxMembers} reached`); + } + if (providerHasModelPreflight(this.deps.provider)) { + this.deps.provider.preflightMemberModel(); + } + this.deps.provider.prepareContinuable?.({ + teamId: this.deps.teamId, + memberId: childId, + name, + description, + firstPrompt: args.prompt, + context, + requestId + }); + await this.deps.store.append({ + type: "team/member", + version: 2, + teamId: this.deps.teamId, + member: memberSnapshotOf(childId, name, description, providerName, context, "provisioning") + }); + }); + const run = (async () => { + const signal = combineSignals(args.signal, this.deps.lifecycle.runtimeSignal()); + const ownershipSignal = args.ownershipSignal; + const runSignal = ownershipSignal === void 0 ? signal : AbortSignal.any([signal, ownershipSignal]); + try { + return await this.deps.provider.startContinuable({ + teamId: this.deps.teamId, + memberId: childId, + name, + description, + firstPrompt: args.prompt, + // 对齐轮:0.2.1 初始任务不含身份前缀 + context, + requestId, + signal: runSignal + }); + } catch (err) { + if (ownershipSignal?.aborted) throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF0C\u521B\u5EFA\u7ED3\u679C\u5F85\u786E\u8BA4"); + throw this.mapAbortToDisposed(err); + } + })(); + let started; + try { + started = await run; + } catch (originalError) { + if (originalError instanceof ProvisioningPending) { + if (!this.deps.lifecycle.runtimeSignal().aborted && !args.ownershipSignal?.aborted) { + this.scheduleProvisioningRecheck(childId); + } + return { member: this.rowOf(childId), creation: "pending", message: originalError.message }; + } + let becameActiveConflict; + let recordError; + let recordErrorSet = false; + try { + const settled2 = await this.settleProvisioning(childId, "failed", errorMessage(originalError)); + if (settled2 === "active") { + becameActiveConflict = new TeamError( + "TEAM_PROVISIONING_CONFLICT", + `teammate "${name}" became active while its creator reported failure` + ); + } + } catch (err) { + recordError = err; + recordErrorSet = true; + } + if (becameActiveConflict !== void 0) { + this.notifyStatus(); + throw becameActiveConflict; + } + if (recordErrorSet) { + throw new AggregateError( + [originalError, recordError], + "teammate creation and durable failure recording both failed" + ); + } + try { + await this.deps.provider.interrupt({ memberId: childId }); + } catch (cleanupError) { + throw new AggregateError( + [originalError, cleanupError], + "teammate creation and durable failure recording both failed" + ); + } + this.notifyStatus(); + throw originalError; + } + if (started.memberId !== childId) { + throw new Error(`provider returned memberId ${started.memberId} != provisioned ${childId}`); + } + if (started.creation === "pending") { + if (!this.deps.lifecycle.runtimeSignal().aborted && !args.ownershipSignal?.aborted) { + this.scheduleProvisioningRecheck(childId); + } + return { member: this.rowOf(childId), creation: "pending", message: "\u7ED3\u679C\u5F85\u786E\u8BA4" }; + } + if (!started.accepted) { + const rejection = new TeamError("TEAM_PROVISIONING_CONFLICT", `teammate "${childId}" initial prompt was not durably accepted`); + await this.settleProvisioning(childId, "failed", rejection.message); + await this.deps.provider.interrupt({ memberId: childId }); + this.notifyStatus(); + throw rejection; + } + const settled = await this.settleProvisioning(childId, "active"); + if (settled === "failed") { + const conflict = new TeamError( + "TEAM_PROVISIONING_CONFLICT", + `teammate "${name}" was reconciled as failed while creation was in progress` + ); + try { + await this.deps.provider.interrupt({ memberId: childId }); + } catch (cleanupError) { + throw new AggregateError([conflict, cleanupError], "provisioning conflict cleanup failed"); + } + throw conflict; + } + this.notifyStatus(); + return { member: this.rowOf(childId) }; + } + /** settleProvisioning(幂等):已非 provisioning → 返回现有相位不追加;成员消失 → C1 冲突。 */ + settleProvisioning(memberId, phase, error2) { + return this.deps.store.transact(async () => { + const state = this.loadState(); + const member = state.members.find((m) => m.id === memberId); + if (member === void 0) { + throw new TeamError("TEAM_PROVISIONING_CONFLICT", `provisioned teammate "${memberId}" disappeared`); + } + if (member.phase !== "provisioning") return member.phase; + const next = error2 !== void 0 ? { ...member, phase, error: error2 } : { ...member, phase }; + await this.deps.store.append({ + type: "team/member", + version: 2, + teamId: this.deps.teamId, + member: next + }); + return phase; + }); + } + // ---------------------------------------------------------------- 恢复对账(§5.4) + /** 对每个 provisioning 且不存活的成员执行四条件对账;C3:恢复自身抛错仅警告。 + * 返回摘要(第四轮最小扩展):orphans = 本轮识别的失联成员;settled = 本轮定案者 + * (active/failed 任一去向;幂等竞态下相位已被他方定案也计入——结局已持久); + * 〔D33〕deferred = 本轮因宽限跳过判定的成员(事件年龄 < graceMs 且 origin 未落盘)。 + * + * 〔D33 事件年龄宽限,2026-11-02〕锁易主/恢复触发的 reconcile 与 in-flight spawn 竞态: + * origin.json 在 createChild 之后才落盘(resume-provider.ts),此前 readProvisioningRecord + * 恒 undefined,旧逻辑会把仍在正常供给的成员误判 failed(sess_cabd748c 实测:锁被假死抢走后 + * 新协调者构造即 reconcile,两个 in-flight 成员被误杀)。现以 journal 中该成员最后一条 + * team/member(provisioning) 事件的 ts 计龄:尚未确认首轮受理(记录缺失或 accepted 未置位) + * 且年龄 < graceMs → 跳过本轮并排一次性 recheck(10s);年龄 ≥ graceMs 或恢复抛错 → 照旧 + * 定案(真故障不被掩盖)。store 未实现 readEventLines(内存桩)→ 无宽限(旧语义)。 */ + async reconcileProvisioning(recheckMemberId) { + const state = this.loadState(); + const pending = state.members.filter( + (m) => m.phase === "provisioning" && (m.id === recheckMemberId || !this.deps.inspector.isAlive(m.id)) + ); + const orphans = pending.map((m) => m.id); + const settled = []; + const deferred = []; + const ages = await this.provisioningEventAges(); + for (const member of pending) { + try { + let failure; + let missingRecord = false; + let active = false; + let recoveryThrew = false; + try { + const record2 = this.deps.recon.readProvisioningRecord(member.id); + if (record2 === void 0) { + missingRecord = true; + } else if (record2.rootSessionId === this.deps.teamId && record2.descriptor !== void 0 && record2.descriptor.mode === "continuable" && record2.descriptor.provider === member.provider && record2.initialUserMessageAccepted) { + active = true; + } else if (record2.rootSessionId === this.deps.teamId && record2.descriptor !== void 0 && record2.descriptor.mode === "continuable" && record2.descriptor.provider === member.provider && !record2.initialUserMessageAccepted) { + missingRecord = true; + } else { + failure = "persisted child Session does not match the provisioned continuation"; + } + } catch (err) { + recoveryThrew = true; + failure = `child Session recovery failed: ${errorMessage(err)}`; + } + if (!active && !recoveryThrew && !missingRecord && failure !== void 0) { + await this.settleProvisioning(member.id, "failed", failure); + settled.push(member.id); + this.notifyStatus(); + continue; + } + if (!active) { + if (this.deps.provider.noteProvisioningRecovery?.(member.id) === true) { + this.recoveryStopped.add(member.id); + deferred.push(member.id); + this.notifyStatus(); + continue; + } + if (this.deps.provider.resumeContinuable !== void 0) { + try { + const resumed = await this.deps.provider.resumeContinuable( + member.id, + this.deps.lifecycle.runtimeSignal() + ); + if (resumed.creation === "pending" || !resumed.accepted) { + deferred.push(member.id); + this.scheduleProvisioningRecheck(member.id); + continue; + } + active = true; + } catch (err) { + if (err instanceof ProvisioningPending) { + deferred.push(member.id); + this.scheduleProvisioningRecheck(member.id); + continue; + } + throw err; + } + } else { + const ageMs = ages?.get(member.id); + if (!recoveryThrew && ageMs !== void 0 && ageMs < PROVISIONING_GRACE_MS) { + deferred.push(member.id); + this.scheduleProvisioningRecheck(member.id); + continue; + } + } + } + await this.settleProvisioning(member.id, active ? "active" : "failed", failure); + settled.push(member.id); + this.notifyStatus(); + } catch (err) { + this.deps.warn?.( + `Agent Teams recovery for "${member.id}" failed: ${err instanceof Error ? err.message : String(err)}` + ); + } + } + return { orphans, settled, deferred }; + } + /** 〔D33〕每个成员最后一条 team/member(provisioning) 事件的年龄(ms);无端口/读失败 → undefined。 */ + async provisioningEventAges() { + const read = this.deps.store.readEventLines; + if (read === void 0) return void 0; + try { + const lines = await read.call(this.deps.store); + const lastTs = /* @__PURE__ */ new Map(); + for (const line of lines) { + const e = line.event; + if (e?.type !== "team/member") continue; + const id = e.member?.id; + if (typeof id !== "string") continue; + if (e.member?.phase !== "provisioning") continue; + const at = Date.parse(line.ts); + if (Number.isNaN(at)) continue; + const prev = lastTs.get(id); + if (prev === void 0 || at > prev) lastTs.set(id, at); + } + const now2 = Date.now(); + const ages = /* @__PURE__ */ new Map(); + for (const [id, at] of lastTs) ages.set(id, now2 - at); + return ages; + } catch { + return void 0; + } + } + /** 〔D33〕defer 后的一次性复核(不阻塞、不叠加:同成员在途则跳过)。 */ + scheduleProvisioningRecheck(memberId) { + if (this.recheckTimers.has(memberId)) return; + const timer = setTimeout(() => { + this.recheckTimers.delete(memberId); + void this.reconcileProvisioning(memberId).then( + () => void 0, + () => void 0 + // C3:对账自身抛错仅警告语义由调用方承担 + ); + }, PROVISIONING_RECHECK_MS); + timer.unref?.(); + this.recheckTimers.set(memberId, timer); + } + hasPendingAutomaticProgress(callerId) { + const { state } = this.requireMember(callerId); + return state.members.some( + (member) => member.phase === "active" && (this.deps.inspector.isAlive(member.id) || this.deps.presentation?.statusOf(member.id) === "running") || member.phase === "provisioning" && !this.recoveryStopped.has(member.id) + ); + } + // ---------------------------------------------------------------- listMembers(§5.5) + listMembers(callerId) { + this.requireMember(callerId); + const state = this.loadState(); + const presentation = this.deps.presentation; + const leadModel = presentation?.leadModelOf?.() ?? this.deps.leadModel; + const rows = [ + { + target: "lead", + role: "lead", + // availability(root):Lead 调用方视角恒 running;teammate 视角无法观测宿主 Lead 回合, + // 保守呈 inactive(D19 登记)。此前恒 running 会让 teammate 的 noProgress 捷径失效。 + status: callerId === state.id ? "running" : "inactive", + ...leadModel !== void 0 ? { model: leadModel } : {}, + diagnostics: [] + } + ]; + for (const member of state.members) { + const status = member.phase === "failed" ? "failed" : member.phase === "provisioning" ? "provisioning" : presentation ? presentation.statusOf(member.id) : this.deps.inspector.isAlive(member.id) ? "running" : "inactive"; + const model = presentation?.modelOf(member.id) ?? this.deps.leadModel; + const extraDiagnostics = presentation?.diagnosticsOf?.(member.id) ?? []; + const diagnostics = [ + ...member.error !== void 0 ? [member.error] : [], + ...extraDiagnostics + ]; + rows.push({ + target: member.name, + role: "teammate", + status, + description: member.description, + provider: member.provider, + context: member.context, + ...model !== void 0 ? { model } : {}, + diagnostics + }); + } + return { members: rows }; + } + // ---------------------------------------------------------------- interrupt(§5.6) + async interrupt(callerId, rawName) { + const { state } = this.requireMember(callerId); + if (callerId !== state.id) { + throw new TeamError("TEAM_LEAD_REQUIRED", "only the Team Lead can interrupt teammates"); + } + const name = rawName.trim(); + if (name === "lead") { + throw new TeamError("TEAM_INVALID_TARGET", "the Team Lead cannot interrupt itself"); + } + const target = state.members.find((m) => m.name === name && m.phase === "active"); + if (target === void 0) { + throw new TeamError("TEAM_MEMBER_NOT_FOUND", `active teammate "${name}" not found`); + } + if (!this.deps.inspector.isAlive(target.id) && this.deps.presentation?.statusOf(target.id) !== "running") { + return { previousStatus: "inactive" }; + } + const result = await this.deps.provider.interrupt({ memberId: target.id }); + this.notifyStatus(); + return result; + } + // ---------------------------------------------------------------- 内部 + /** C2③:checkpoint 等待被非 Error reason 中止 → TEAM_DISPOSED `teammate creation aborted: `。 */ + mapAbortToDisposed(err) { + if (err instanceof Error) return err; + return new TeamError("TEAM_DISPOSED", `teammate creation aborted: ${errorMessage(err)}`); + } + rowOf(memberId) { + const rows = this.listMembers(this.deps.teamId).members; + const row = rows.find((r) => r.target === this.nameOf(memberId)); + if (row === void 0) throw new Error(`member row missing for ${memberId}`); + return row; + } + nameOf(memberId) { + const member = this.loadState().members.find((m) => m.id === memberId); + return member?.name ?? ""; + } + notifyStatus() { + for (const listener of this.statusListeners) listener(); + } +}; +function memberSnapshotOf(id, name, description, provider, context, phase, error2) { + return { id, name, description, provider, context, phase, ...error2 !== void 0 ? { error: error2 } : {} }; +} +var ProvisioningPending = class extends Error { + constructor(message = "\u7ED3\u679C\u5F85\u786E\u8BA4") { + super(message); + this.name = "ProvisioningPending"; + } +}; +function defaultNewId() { + return globalThis.crypto.randomUUID(); +} +function combineSignals(a, b) { + if (a === void 0) return b; + return AbortSignal.any([a, b]); +} + +// src/domain/mailbox.ts +function resolveActiveMember(state, teamId, rawName) { + const name = rawName.trim(); + if (name === "lead") return { id: teamId, name: "lead" }; + const member = state.members.find((m) => m.name === name && m.phase === "active"); + if (member === void 0) { + throw new TeamError("TEAM_MEMBER_NOT_FOUND", `active teammate "${name}" not found`); + } + return { id: member.id, name: member.name }; +} +function frameMessage(message) { + return [ + { type: "text", text: `Team message from ${message.senderName}:` }, + ...message.content + ]; +} +function utf8Bytes(text) { + return new TextEncoder().encode(text).length; +} +var TeamMailbox = class { + constructor(deps) { + this.deps = deps; + } + targetChains = /* @__PURE__ */ new Map(); + inflight = /* @__PURE__ */ new Map(); + /** send(对齐轮修订):校验 → pending 落盘 flush(先于任何投递尝试)→ tryDispatch 同步发起(B6)。 */ + async send(callerId, args) { + return this.deps.lifecycle.track(this.sendInner(callerId, args)); + } + async sendInner(callerId, args) { + const membership = requireMembership(() => this.loadState(), callerId); + this.deps.lifecycle.requireOpen(); + let messageId; + let dispatch2; + await this.deps.store.transact(async () => { + const state = this.loadState(); + const target = resolveActiveMember(state, this.deps.teamId, args.target); + if (target.id === callerId) { + throw new TeamError("TEAM_SELF_MESSAGE", "a Team member cannot message itself"); + } + const id = `team-message-${(this.deps.newId ?? defaultNewId2)()}`; + const snapshot = { + id, + senderId: callerId, + senderName: membership.name, + targetId: target.id, + content: structuredClone(args.content) + }; + const framed = frameMessage(snapshot); + const bytes = utf8Bytes(JSON.stringify(framed)); + if (bytes > this.deps.limits.maxMessageBytes) { + throw new TeamError("TEAM_MESSAGE_TOO_LARGE", `team message exceeds ${this.deps.limits.maxMessageBytes} bytes`); + } + await this.deps.store.append({ + type: "team/message/queued", + version: 2, + teamId: this.deps.teamId, + message: snapshot + }); + messageId = id; + dispatch2 = this.tryDispatch(snapshot); + }); + const outcome = await dispatch2; + if (outcome.status === "rejected") { + throw new Error( + `team message could not be delivered to "${args.target}": ${outcome.reason ?? "unknown delivery failure"}` + ); + } + return { + messageId, + status: outcome.status, + ...outcome.reason !== void 0 ? { reason: outcome.reason } : {} + }; + } + /** C5 服务层落点。 */ + loadState() { + const state = this.deps.store.state(); + if (state.failure !== void 0) throw new Error(state.failure); + return state; + } + pendingCount(state, targetId) { + const deliveredIds = new Set(state.delivered); + return state.messages.filter((m) => m.targetId === targetId && !deliveredIds.has(m.id)).length; + } + /** 目标的全部 pending(队列序)。 */ + pendingFor(state, targetId) { + const deliveredIds = new Set(state.delivered); + return state.messages.filter((m) => m.targetId === targetId && !deliveredIds.has(m.id)); + } + // ---------------------------------------------------------------- 投递(§6.3) + /** 单消息入口:in-flight 去重 + C10 短路 + 按目标串行(dispatchThrough)。 */ + tryDispatch(message) { + const state = this.loadState(); + if (!this.pendingFor(state, message.targetId).some((m) => m.id === message.id)) { + return Promise.resolve({ status: "accepted" }); + } + const existing = this.inflight.get(message.id); + if (existing !== void 0) return existing; + const prev = this.targetChains.get(message.targetId) ?? Promise.resolve(); + const attempt = prev.then( + () => this.dispatchThrough(message), + () => this.dispatchThrough(message) + ); + this.inflight.set( + message.id, + attempt.finally(() => this.inflight.delete(message.id)) + ); + this.targetChains.set( + message.targetId, + attempt.then( + () => void 0, + () => void 0 + ) + ); + return this.inflight.get(message.id); + } + /** 取该目标全部 pending,按队列序投递直到本条;前序 pending/rejected 即整体返回该结果。 */ + async dispatchThrough(message) { + const state = this.loadState(); + const queue = this.pendingFor(state, message.targetId); + for (const candidate of queue) { + const outcome = await this.dispatchOne(candidate); + if (candidate.id === message.id) return outcome; + if (outcome.status !== "accepted") return outcome; + } + return { status: "accepted" }; + } + /** dispatchOnce 分支矩阵(§6.3):accepted=确认送达;pending=适配层收件箱;rejected=硬失败。 */ + async dispatchOne(message) { + try { + const framed = frameMessage(message); + const source = { + kind: "agent-message", + form: "relay", + senderSessionId: message.senderId + }; + if (message.targetId === this.deps.teamId) { + const steered = this.deps.steerLead ? this.deps.steerLead(framed, source) : defaultSteerLead(framed, source); + if (steered !== false) { + return await this.tryMarkDelivered(message); + } + if (this.deps.inspector.containsMessage(message.targetId, message.id)) { + return await this.tryMarkDelivered(message); + } + return { status: "pending", reason: "lead inbox has no receipt yet" }; + } + if (this.deps.inspector.isAlive(message.targetId)) { + if (this.deps.inspector.containsMessage(message.targetId, message.id)) { + return await this.tryMarkDelivered(message); + } + const verdict2 = await this.deliverFramed(message, framed); + if (verdict2 === "accepted") return await this.checkpointDelivered(message); + return { status: "pending", reason: "target is running; delivery deferred to turn boundary" }; + } + let record2; + try { + record2 = this.deps.inspector.readColdRecord(message.targetId, message.id); + } catch (err) { + this.deps.warn?.( + `cannot read Team message target "${message.targetId}": ${errText(err)}` + ); + return { status: "rejected", reason: errText(err) }; + } + if (record2 !== void 0 && record2.recorded) { + return await this.tryMarkDelivered(message); + } + const verdict = await this.deliverFramed(message, framed); + if (verdict === "accepted") return await this.checkpointDelivered(message); + return { status: "pending", reason: "cold target resume deferred" }; + } catch (err) { + this.deps.warn?.(`team message "${message.id}" remains queued: ${errText(err)}`); + return { status: "rejected", reason: errText(err) }; + } + } + /** provider.deliver(framedMessage 序列化为字符串——草案 §1 deliver 签名)。 */ + deliverFramed(message, framed) { + return this.deps.provider.deliver({ + memberId: message.targetId, + framedMessage: JSON.stringify(framed), + messageId: message.id + }); + } + /** §6.3 checkpointDelivered:确认目标日志确已含该消息身份,再 markDelivered(幂等)。 */ + async checkpointDelivered(message) { + const confirmed = message.targetId === this.deps.teamId || this.deps.inspector.containsMessage(message.targetId, message.id); + if (!confirmed) { + this.deps.warn?.(`team message "${message.id}" remains queued: target confirmation missing`); + return { status: "pending", reason: "target confirmation missing" }; + } + return await this.tryMarkDelivered(message); + } + /** + * 投递已发生但 delivered 事件未落盘(如 journal 崩溃/确认缺失):返回 pending, + * 由恢复路径按 containsMessage 补记;不向调用方谎报 accepted,也不误报 rejected。 + */ + async tryMarkDelivered(message) { + try { + await this.markDelivered(message); + return { status: "accepted" }; + } catch (err) { + this.deps.warn?.(`team message "${message.id}" delivered confirmation not recorded: ${errText(err)}`); + return { status: "pending", reason: "delivered confirmation not recorded" }; + } + } + /** markDelivered(幂等:已 delivered / 消息不存在 / targetId 不符 → 静默返回)。 */ + async markDelivered(message) { + await this.deps.store.transact(async () => { + const state = this.loadState(); + const existing = state.messages.find((m) => m.id === message.id); + if (existing === void 0) return; + if (existing.targetId !== message.targetId) return; + if (state.delivered.includes(message.id)) return; + await this.deps.store.append({ + type: "team/message/delivered", + version: 2, + teamId: this.deps.teamId, + messageId: message.id, + targetId: message.targetId + }); + }); + } + // ---------------------------------------------------------------- 回执观察与恢复重试(F20) + /** §6.3 回执观察(全局 session/event 等价钩子):目标已持久接收 → 补记 delivered。 */ + async observeDelivery(memberId, messageId) { + try { + const state = this.loadState(); + const message = state.messages.find((m) => m.id === messageId); + if (message === void 0 || message.targetId !== memberId) return; + if (state.delivered.includes(messageId)) return; + if (this.deps.inspector.containsMessage(memberId, messageId)) { + await this.markDelivered(message); + } + } catch (err) { + this.deps.warn?.(`Team message "${messageId}" acknowledgement failed: ${errText(err)}`); + } + } + /** §6.3 恢复重试:成员启动 → 其 pending 重投;Lead("all")→ 全量。 */ + async recoverFor(target) { + const state = this.loadState(); + const targets = target === "all" ? [...new Set(state.messages.map((m) => m.targetId))] : [target]; + for (const targetId of targets) { + const queue = this.pendingFor(this.loadState(), targetId); + if (process.env.TEAM_DEBUG_DELIVERY === "1") { + this.deps.warn?.(`delivery-recover target=${targetId} pending=${queue.length}`); + } + for (const message of queue) { + const outcome = await this.tryDispatch(message); + if (process.env.TEAM_DEBUG_DELIVERY === "1") { + this.deps.warn?.(`delivery-recover target=${targetId} message=${message.id} status=${outcome.status} reason=${outcome.reason ?? ""}`); + } + } + } + } +}; +function defaultSteerLead(framed, source) { +} +function defaultNewId2() { + return globalThis.crypto.randomUUID(); +} +function errText(err) { + return err instanceof Error ? err.message : String(err); +} + +// src/domain/taskboard.ts +var TeamTaskBoard = class { + constructor(deps) { + this.deps = deps; + } + // ---------------------------------------------------------------- create(§7.2) + async create(callerId, args) { + this.requireMember(callerId); + this.deps.lifecycle.requireOpen(); + const subject = requiredText("subject", args.subject, 200); + const description = requiredText("description", args.description, 16384); + const scopes = writeScopes(args.writeScopes ?? []); + return this.deps.store.transact(async () => { + const state = this.loadState(); + const id = `task-${state.nextTaskNumber}`; + if (state.nextTaskNumber > Number.MAX_SAFE_INTEGER || state.tasks.some((t) => t.id === id)) { + throw new TeamError("TEAM_TASK_LIMIT", "Team task id space exhausted"); + } + const liveCount = state.tasks.filter((t) => t.status !== "deleted").length; + if (liveCount >= this.deps.limits.maxTasks) { + throw new TeamError("TEAM_TASK_LIMIT", `Team task limit ${this.deps.limits.maxTasks} reached`); + } + dependencies(state.tasks, id, args.blockedBy ?? []); + const task = { + id, + revision: 1, + subject, + description, + status: "pending", + blockedBy: [...args.blockedBy ?? []], + writeScopes: scopes + }; + assertTaskGraphCandidate(state.tasks, task); + const { state: next } = await this.deps.store.append({ + type: "team/task", + version: 2, + teamId: this.deps.teamId, + task + }); + return { task: projectTaskView(next, next.tasks.find((t) => t.id === id)) }; + }); + } + // ---------------------------------------------------------------- update(§7.3) + async update(callerId, args) { + this.requireMember(callerId); + this.deps.lifecycle.requireOpen(); + return this.deps.store.transact(async () => { + const state = this.loadState(); + const current = state.tasks.find((t) => t.id === args.taskId); + if (current === void 0) { + throw new TeamError("TEAM_TASK_NOT_FOUND", `team task "${args.taskId}" not found`); + } + if (current.revision !== args.expectedRevision) { + throw new TeamError( + "TEAM_TASK_STALE_REVISION", + `stale team task "${args.taskId}" revision ${args.expectedRevision}; current revision is ${current.revision}` + ); + } + if (current.status === "deleted") { + throw new TeamError("TEAM_TASK_DELETED", `team task "${args.taskId}" is deleted`); + } + const isLead = callerId === state.id; + const isOwner = current.ownerId === callerId; + const next = this.applyAction(state, current, callerId, isLead, isOwner, args); + assertTaskGraphCandidate(state.tasks, next); + const { state: nextState } = await this.deps.store.append({ + type: "team/task", + version: 2, + teamId: this.deps.teamId, + task: next + }); + return { + task: projectTaskView(nextState, nextState.tasks.find((t) => t.id === args.taskId)) + }; + }); + } + applyAction(state, current, callerId, isLead, isOwner, args) { + const authorizeOwner = () => { + if (!(isLead || isOwner)) { + throw new TeamError("TEAM_TASK_UNAUTHORIZED", "task mutation requires its owner or Team Lead"); + } + }; + const ready = projectTaskView(state, current).ready; + const bump = (patch) => ({ + ...current, + ...patch, + revision: current.revision + 1 + }); + switch (args.action) { + case "claim": { + if (current.ownerId !== void 0 && current.ownerId !== callerId) { + throw new TeamError( + "TEAM_TASK_ALREADY_CLAIMED", + `team task "${current.id}" is owned by another member` + ); + } + if (current.status !== "pending" || !ready) { + throw new TeamError("TEAM_TASK_BLOCKED", `team task "${current.id}" is not ready to claim`); + } + return bump({ status: "in_progress", ownerId: callerId }); + } + case "release": { + authorizeOwner(); + if (current.status !== "in_progress") { + throw new TeamError("TEAM_TASK_INVALID_TRANSITION", "only an in-progress task can be released"); + } + return stripOwner(bump({ status: "pending" })); + } + case "edit": { + authorizeOwner(); + const hasAny = args.subject !== void 0 || args.description !== void 0 || args.writeScopes !== void 0; + if (!hasAny) { + throw new TeamError( + "TEAM_INVALID_ARGUMENT", + "task edit requires subject, description, or write_scopes" + ); + } + return bump({ + ...args.subject !== void 0 ? { subject: requiredText("subject", args.subject, 200) } : {}, + ...args.description !== void 0 ? { description: requiredText("description", args.description, 16384) } : {}, + ...args.writeScopes !== void 0 ? { writeScopes: writeScopes(args.writeScopes) } : {} + }); + } + case "set_dependencies": { + authorizeOwner(); + if (args.blockedBy === void 0) { + throw new TeamError("TEAM_INVALID_ARGUMENT", "set_dependencies requires blocked_by"); + } + dependencies(state.tasks, current.id, args.blockedBy); + return bump({ blockedBy: [...args.blockedBy] }); + } + case "complete": { + authorizeOwner(); + if (current.status !== "in_progress") { + throw new TeamError("TEAM_TASK_INVALID_TRANSITION", "only an in-progress task can complete"); + } + return bump({ status: "completed" }); + } + case "reopen": { + authorizeOwner(); + if (current.status !== "completed") { + throw new TeamError("TEAM_TASK_INVALID_TRANSITION", "only a completed task can reopen"); + } + return stripOwner( + bump({ + status: "pending", + ...args.description !== void 0 ? { description: requiredText("description", args.description, 16384) } : {} + }) + ); + } + case "reassign": { + if (!isLead) { + throw new TeamError("TEAM_LEAD_REQUIRED", "only the Team Lead can reassign tasks"); + } + if (current.status !== "pending" && current.status !== "in_progress") { + throw new TeamError( + "TEAM_TASK_INVALID_TRANSITION", + "only a pending or in-progress task can be reassigned" + ); + } + const rawOwner = (args.owner ?? "").trim(); + if (rawOwner.length === 0) { + return stripOwner(bump({ status: "pending" })); + } + if (!ready) { + throw new TeamError("TEAM_TASK_BLOCKED", `team task "${current.id}" is blocked`); + } + const target = rawOwner === "lead" ? { id: state.id, name: "lead" } : state.members.find((m) => m.name === rawOwner && m.phase === "active"); + if (target === void 0) { + throw new TeamError("TEAM_MEMBER_NOT_FOUND", `active teammate "${rawOwner}" not found`); + } + return bump({ status: "in_progress", ownerId: target.id }); + } + case "delete": { + authorizeOwner(); + const dependent = state.tasks.find( + (t) => t.id !== current.id && t.status !== "deleted" && t.blockedBy.includes(current.id) + ); + if (dependent !== void 0) { + throw new TeamError( + "TEAM_TASK_HAS_DEPENDENTS", + `team task "${current.id}" still blocks "${dependent.id}"` + ); + } + return bump({ status: "deleted" }); + } + default: + throw new TeamError("TEAM_INVALID_ARGUMENT", `unsupported task action ${String(args.action)}`); + } + } + // ---------------------------------------------------------------- list / get(§7.6) + list(callerId, args = {}) { + this.requireMember(callerId); + const state = this.loadState(); + const cursor = args.cursor ?? 0; + const limit = args.limit ?? 50; + if (!Number.isSafeInteger(cursor) || cursor < 0) { + throw new TeamError("TEAM_INVALID_ARGUMENT", "cursor must be a non-negative safe integer"); + } + if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) { + throw new TeamError("TEAM_INVALID_ARGUMENT", "limit must be an integer from 1 through 100"); + } + const views = state.tasks.filter((t) => t.status !== "deleted").map((t) => projectTaskView(state, t)); + const filtered = views.filter((view2) => { + if (args.status !== void 0 && view2.status !== args.status) return false; + if (args.owner !== void 0) { + if (args.owner === "unowned" && view2.ownerName !== void 0) return false; + if (args.owner !== "unowned" && view2.ownerName !== args.owner) return false; + } + if (args.ready !== void 0 && view2.ready !== args.ready) return false; + return true; + }); + const page = filtered.slice(cursor, cursor + limit); + const hasNext = cursor + limit < filtered.length; + return hasNext ? { tasks: page, nextCursor: cursor + limit } : { tasks: page }; + } + get(callerId, taskId) { + this.requireMember(callerId); + const state = this.loadState(); + const task = state.tasks.find((t) => t.id === taskId); + if (task === void 0) { + throw new TeamError("TEAM_TASK_NOT_FOUND", `team task "${taskId}" not found`); + } + return { task: projectTaskView(state, task) }; + } + // ---------------------------------------------------------------- 内部 + requireMember(callerId) { + requireMembership(() => this.loadState(), callerId); + } + loadState() { + const state = this.deps.store.state(); + if (state.failure !== void 0) throw new Error(state.failure); + return state; + } +}; +function stripOwner(task) { + if (task.ownerId === void 0) return task; + const clone2 = { ...task }; + delete clone2.ownerId; + return clone2; +} + +// src/domain/runtime.ts +var TeamRuntime = class { + lifecycle; + activity; + roster; + mailbox; + taskboard; + unsubscribeCommit; + unsubscribeStatus; + constructor(deps) { + const generationAbort = new AbortController(); + deps.signal?.addEventListener("abort", () => { + this.lifecycle.revokeGeneration(deps.signal?.reason); + this.roster.cancelPendingRecovery(); + }, { once: true }); + this.lifecycle = new TeamLifecycle({ + teamId: deps.teamId, + store: deps.store, + disposalTimeoutMs: deps.limits.disposalTimeoutMs, + drainer: (args) => deps.provider.drain({ teamId: deps.teamId, timeoutMs: args.timeoutMs }), + closeWaiters: () => this.activity.closeAll(), + clock: deps.clock + }); + this.activity = new TeamActivity({ store: deps.store, clock: deps.clock }); + this.roster = new TeamRoster({ + teamId: deps.teamId, + store: deps.store, + provider: deps.provider, + recon: deps.provider, + inspector: deps.provider, + limits: deps.limits, + lifecycle: this.lifecycle, + presentation: deps.presentation, + providers: deps.providers, + leadModel: deps.leadModel, + warn: deps.warn, + newId: deps.newId + }); + this.mailbox = new TeamMailbox({ + teamId: deps.teamId, + store: deps.store, + provider: deps.provider, + inspector: deps.provider, + limits: deps.limits, + lifecycle: this.lifecycle, + steerLead: deps.steerLead, + warn: deps.warn, + newId: deps.newId + }); + this.taskboard = new TeamTaskBoard({ + teamId: deps.teamId, + store: deps.store, + limits: deps.limits, + lifecycle: this.lifecycle + }); + this.unsubscribeCommit = this.activity.bindCommitEdge(); + this.unsubscribeStatus = this.roster.onMemberStatus(() => this.activity.notifyMemberStatus()); + } + /** 冷启动恢复对账:roster 对账完成 + 全量邮箱续投。 */ + async recoverAll() { + await this.roster.startRecovery(); + await this.mailbox.recoverFor("all"); + } + /** D9 抽象处置入口。 */ + dispose(reason) { + return this.lifecycle.dispose(reason); + } + close() { + this.unsubscribeCommit(); + this.unsubscribeStatus(); + this.roster.cancelPendingRecovery(); + this.activity.closeAll(); + } +}; + +// src/provider/mock-provider.ts +import { randomUUID as randomUUID2 } from "node:crypto"; +var MockProvider = class { + teamChildren = /* @__PURE__ */ new Map(); + /** 非团队子进程(§12「非 Team 的 continuable 子代理不动」验证)。 */ + foreignChildren = /* @__PURE__ */ new Set(); + provisioningRecords = /* @__PURE__ */ new Map(); + drainedTeamIds = []; + drainCalls = 0; + startCalls = 0; + prepared = []; + deliverCalls = 0; + interruptCalls = 0; + /** 默认无自动恢复能力(保留纯域 mock 旧语义);专项测试可注入持久预算行为。 */ + noteProvisioningRecovery; + resumeContinuable; + generationAbort = new AbortController(); + activateGeneration() { + this.generationAbort = new AbortController(); + return this.generationAbort.signal; + } + get generationSignal() { + return this.generationAbort.signal; + } + detach() { + this.generationAbort.abort(new Error("coordinator generation revoked")); + } + program = {}; + deliverScript = []; + programWith(program) { + this.program = program; + this.deliverScript = program.deliverResults ? [...program.deliverResults] : []; + return this; + } + prepareContinuable(args) { + this.prepared.push({ name: args.name, prompt: args.firstPrompt, requestId: args.requestId, context: args.context }); + } + requestStatus(requestId) { + const intent = this.prepared.find((entry) => entry.requestId === requestId); + const member = intent === void 0 ? void 0 : [...this.teamChildren.values()].find((child) => child.name === intent.name); + return intent === void 0 ? void 0 : { memberId: member?.memberId ?? `mock-${intent.name}`, accepted: member?.received.has("") ?? false }; + } + async startContinuable(args) { + this.startCalls += 1; + const outcome = this.program.startOutcome ?? { kind: "accept" }; + if (this.program.startDelayMs && this.program.startDelayMs > 0) { + await sleep3(this.program.startDelayMs); + } + if (outcome.kind === "hang") { + await new Promise((_, reject) => { + const onAbort = () => reject(args.signal?.reason ?? new Error("aborted")); + if (args.signal?.aborted) return onAbort(); + args.signal?.addEventListener("abort", onAbort, { once: true }); + }); + } + if (outcome.kind === "throw") throw outcome.error; + if (outcome.kind === "pending") return { memberId: args.memberId, accepted: false, creation: "pending" }; + const child = { + memberId: args.memberId, + name: args.name, + context: args.context, + model: void 0, + modelSelection: void 0, + firstPrompt: args.firstPrompt, + alive: true, + received: /* @__PURE__ */ new Set(), + deliverCount: /* @__PURE__ */ new Map(), + interrupted: 0, + drained: false, + status: "running" + // 首轮 prompt 已投递 → 存活即 running(availability 口径) + }; + this.teamChildren.set(args.memberId, child); + this.provisioningRecords.set(args.memberId, { + rootSessionId: args.teamId, + descriptor: { provider: args.context === "fork" ? "fork" : "spawn", mode: "continuable" }, + initialUserMessageAccepted: outcome.kind === "accept" + }); + return { memberId: args.memberId, accepted: outcome.kind === "accept" }; + } + async deliver(args) { + this.deliverCalls += 1; + if (this.program.deliverDelayMs && this.program.deliverDelayMs > 0) { + await sleep3(this.program.deliverDelayMs); + } + const child = this.teamChildren.get(args.memberId); + if (child === void 0 || !child.alive) { + if (this.program.coldDeliverOutcome === "accepted") { + const cold = child ?? { + memberId: args.memberId, + name: args.memberId, + context: "fresh", + model: void 0, + modelSelection: void 0, + firstPrompt: "", + alive: false, + received: /* @__PURE__ */ new Set(), + deliverCount: /* @__PURE__ */ new Map(), + interrupted: 0, + drained: false, + status: "idle" + }; + if (!cold.received.has(args.messageId)) { + cold.received.add(args.messageId); + cold.deliverCount.set(args.messageId, (cold.deliverCount.get(args.messageId) ?? 0) + 1); + } + if (child === void 0) this.teamChildren.set(args.memberId, cold); + return "accepted"; + } + return "queued"; + } + const verdict = this.deliverScript.length > 0 ? this.deliverScript.shift() : "accepted"; + if (verdict === "throw") throw new Error(`mock deliver failure for ${args.messageId}`); + if (verdict === "lost") { + return "accepted"; + } + if (verdict === "queued") { + return "queued"; + } + if (child.received.has(args.messageId)) { + return "accepted"; + } + child.received.add(args.messageId); + child.deliverCount.set(args.messageId, (child.deliverCount.get(args.messageId) ?? 0) + 1); + return "accepted"; + } + async interrupt(args) { + if (this.program.interruptError !== void 0) throw this.program.interruptError; + this.interruptCalls += 1; + const child = this.teamChildren.get(args.memberId); + if (child === void 0 || !child.alive) return { previousStatus: "inactive" }; + const previousStatus = child.status; + child.interrupted += 1; + child.status = "idle"; + return { previousStatus }; + } + async drain(args) { + this.drainCalls += 1; + if (this.program.drainError !== void 0) throw this.program.drainError; + await sleep3(Math.min(args.timeoutMs, 5)); + for (const child of this.teamChildren.values()) { + if (child.alive) { + child.alive = false; + child.drained = true; + } + } + this.drainedTeamIds.push(args.teamId); + } + // ------------------------------------------------ ReconciliationSource(§5.4 桩) + readProvisioningRecord(memberId) { + return this.provisioningRecords.get(memberId); + } + /** 测试直改桩(构造四条件缺失场景)。 */ + setProvisioningRecord(memberId, record2) { + if (record2 === void 0) this.provisioningRecords.delete(memberId); + else this.provisioningRecords.set(memberId, record2); + } + // ------------------------------------------------ TargetInspector(§5.5/§6.3) + isAlive(memberId) { + const child = this.teamChildren.get(memberId); + return child !== void 0 && child.alive; + } + containsMessage(memberId, messageId) { + const child = this.teamChildren.get(memberId); + if (child === void 0) return this.readColdRecord(memberId, messageId)?.recorded ?? false; + return child.received.has(messageId); + } + readColdRecord(memberId, messageId) { + if (this.program.coldRead === "throw") { + throw new Error(`mock cold read failure for ${memberId}`); + } + const child = this.teamChildren.get(memberId); + if (child === void 0) return void 0; + return { recorded: child.received.has(messageId) }; + } + /** 测试辅助:外部把某消息标记为目标已持久接收(F20 回执观察等价钩子)。 */ + markReceived(memberId, messageId) { + const child = this.teamChildren.get(memberId); + if (child) child.received.add(messageId); + } + /** 测试辅助:非团队子进程登记(drain 不动它们)。 */ + addForeignChild(memberId) { + this.foreignChildren.add(memberId); + } + /** 测试辅助:成员生死控制(成员启动/退出模拟)。 */ + killChild(memberId) { + const child = this.teamChildren.get(memberId); + if (child) child.alive = false; + } + reviveChild(memberId) { + const child = this.teamChildren.get(memberId); + if (child) child.alive = true; + } + // §5.5 呈现能力(listMembers 的 availability/model) + statusOf(memberId) { + return this.isAlive(memberId) ? "running" : "inactive"; + } + modelOf(memberId) { + const child = this.teamChildren.get(memberId); + return child?.modelSelection?.modelId ?? child?.model; + } + /** Lead 行模型桩(可编程;缺省 undefined → roster 回落 deps.leadModel)。 */ + leadModelOf() { + return this.program.leadModel; + } + /** 成员附加诊断桩(MemberPresentation.diagnosticsOf;缺省空)。 */ + diagnosticsOf(memberId) { + return this.program.memberDiagnostics?.[memberId] ?? []; + } + /** spawn 预检桩(0.4.1 ModelPreflight;programWith({preflightError}) 注入失败)。 */ + preflightMemberModel() { + if (this.program.preflightError !== void 0) throw this.program.preflightError; + } + newId() { + return randomUUID2(); + } +}; +function sleep3(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// src/coord/host.ts +var DEFAULT_HOST_LIMITS = { + maxMembers: 8, + maxTasks: 256, + maxMessageBytes: 65536, + disposalTimeoutMs: 5e3 +}; +var TeamCoordinatorHost = class _TeamCoordinatorHost { + constructor(dataRoot, teamId, opts, lock, limits, provider) { + this.dataRoot = dataRoot; + this.teamId = teamId; + this.opts = opts; + this.lock = lock; + this.limits = limits; + this.provider = provider; + } + mode = "proxy"; + store = null; + runtime = null; + server = null; + table = null; + watcher = null; + /** pending 补投扫描(崩溃/瞬时失败后不得永久滞留;边界之外的兜底)。 */ + deliveryTimer = null; + promoting = null; + closed = false; + initialLoad = null; + /** 投影 failure 终态 → 降级服务(见 serve())。 */ + degradedReason; + static async open(opts) { + const paths = teamPaths(opts.dataRoot, opts.teamId); + ensureTeamDir(paths); + let host; + const lock = new CoordinatorLock(paths.lockFile, paths.auditFile, { + // 失锁 = 立即降级;不能继续以 coordinator 身份写 journal/占用 socket。 + onLost: () => { + if (providerHasGeneration(host.provider)) host.provider.detach?.(); + void host.demoteToProxy("coordinator lock lost"); + } + }); + lock.installExitHandlers(); + const limits = validateTeamLimits({ ...DEFAULT_HOST_LIMITS, ...opts.limits }); + host = new _TeamCoordinatorHost(opts.dataRoot, opts.teamId, opts, lock, limits, opts.provider ?? new MockProvider()); + try { + await lock.acquire({ waitMs: opts.lockWaitMs ?? 0 }); + } catch (err) { + if (err instanceof AcquireTimeout) { + host.startTakeoverWatcher(); + return host; + } + throw err; + } + const startup = host.serve().then(() => host.currentMode === "coordinator"); + host.promoting = startup; + try { + await startup; + } finally { + if (host.promoting === startup) host.promoting = null; + } + return host; + } + get currentMode() { + return this.mode; + } + get socketPath() { + return this.server?.socketPath; + } + get committedSeq() { + return this.store?.committedSeq ?? this.initialLoad?.seq ?? 0; + } + get coordinatorBootId() { + return this.lock.info?.bootId ?? bootId(); + } + /** 外层断连后只读原请求登记,不通过此入口执行写操作。 */ + get providerForRead() { + return this.provider; + } + /** 代理模式下的方法表(§2 一致性断言用;协调者模式为 null)。 */ + get methodTable() { + return this.table; + } + /** 降级原因(投影 failure 终态);未降级为 undefined。 */ + get degradedFailure() { + return this.degradedReason; + } + /** + * 协调者模式下的域运行时(stage-3 工具面接线用:list_agents 的 MEMBER_VIEW 全保真 + * 与 wait 捷径需要 roster 呈现;附加式小改,披露于 stage-3 开发记录)。 + * 代理模式为 null(本进程无 runtime)。 + */ + get teamRuntime() { + return this.mode === "coordinator" ? this.runtime : null; + } + /** 协调者就绪信息(socketPath/seq;代理模式仅 seq 本地重放值)。 */ + async readyInfo() { + if (this.mode === "coordinator") { + return { + mode: this.mode, + socketPath: this.socketPath, + seq: this.committedSeq, + fromCheckpoint: this.initialLoad?.fromCheckpoint ?? false, + lockInfo: this.lock.info ?? void 0, + ...this.degradedReason !== void 0 ? { failure: this.degradedReason } : {} + }; + } + const loaded = await load(this.paths().teamDir, this.teamId); + return { + mode: this.mode, + seq: loaded.seq, + fromCheckpoint: loaded.fromCheckpoint, + ...loaded.state.failure !== void 0 ? { failure: loaded.state.failure } : {} + }; + } + /** + * 变更/查询分发:协调者模式 → 方法表直执行(与 socket 路径同一份处理器,语义等价); + * 代理模式 → 经 socket 调当前协调者(缺位窗口错误由调用方/TeamClient 决定重试策略)。 + */ + async dispatch(method, params, opts = {}) { + if (this.mode === "coordinator" && this.table !== null) { + return invokeTeamMethod(this.table, method, params, opts); + } + const { teamDir } = this.paths(); + return callCoordinator(teamDir, this.teamId, method, params, { + // 慢方法(spawn/send)用 per-method 裕量;其余沿用 host 全局(缺省交给 RPC 层 15s)。 + timeoutMs: methodTimeoutMs(method) ?? this.opts.callTimeoutMs, + ...opts.signal !== void 0 ? { signal: opts.signal } : {} + }); + } + /** 本地重放读(两模式皆可;协调者模式等价于内存态,代理模式为权威盘面)。 */ + async readBoard() { + return load(this.paths().teamDir, this.teamId); + } + /** 手动触发一次接任尝试(观察者外的显式入口;测试/演练用)。 */ + tryPromote() { + if (this.mode === "coordinator" || this.promoting !== null) { + return this.promoting ?? Promise.resolve(true); + } + const run = this.promoteOnce().finally(() => { + this.promoting = null; + }); + this.promoting = run; + return run; + } + async close() { + if (this.closed) return; + this.closed = true; + this.stopWatcher(); + this.stopDeliverySweep(); + const errors = []; + if (this.server !== null) { + try { + await this.server.close(); + } catch (err) { + errors.push(err); + } + this.server = null; + } + if (this.runtime !== null) { + try { + await this.runtime.dispose(); + } catch (err) { + errors.push(err); + } + this.runtime.close(); + this.runtime = null; + } + if (this.store !== null) { + try { + await this.store.close(); + } catch (err) { + errors.push(err); + } + this.store = null; + } + try { + await this.lock.release(); + } catch (err) { + errors.push(err); + } + if (providerHasGeneration(this.provider)) { + try { + this.provider.detach?.(); + } catch (err) { + errors.push(err); + } + } + this.table = null; + if (errors.length > 0) throw new AggregateError(errors, "Agent Teams coordinator host close failed"); + } + /** + * 失锁降级:停止心跳/写路径,关闭 RPC 与 runtime,回到 proxy 并重新观察接任。 + * 与 close() 的区别:不置 closed,仍可再次晋升。 + */ + async demoteToProxy(reason) { + if (this.closed) return; + this.mode = "proxy"; + if (providerHasGeneration(this.provider)) this.provider.detach?.(); + this.lock.stopHeartbeat(); + this.stopDeliverySweep(); + this.opts.warn?.(`agent-team coordinator demoted for team "${this.teamId}": ${reason}`); + const server2 = this.server; + this.server = null; + this.table = null; + if (server2 !== null) { + try { + await server2.close(); + } catch { + } + removeSocketRegistryIf(this.paths().teamDir, server2.socketPath); + } + const runtime = this.runtime; + this.runtime = null; + if (runtime !== null) { + runtime.close(); + } + const store = this.store; + this.store = null; + if (store !== null) { + try { + await store.close({ checkpoint: false }); + } catch { + } + } + this.startTakeoverWatcher(); + } + // ---------------------------------------------------------------- 内部 + paths() { + return teamPaths(this.dataRoot, this.teamId); + } + /** 轮次边界(stage-4):landed → observeDelivery 折叠 delivered;teammate → pending 续投;状态边 → Activity 唤醒。 */ + async handleTurnBoundary(event) { + if (this.mode !== "coordinator" || this.runtime === null || this.closed) return; + try { + for (const messageId of event.landedMessageIds) { + await this.runtime.mailbox.observeDelivery(event.memberId, messageId); + } + if (event.memberId !== this.teamId) { + await this.runtime.mailbox.recoverFor(event.memberId); + } + this.runtime.roster.notifyStatusChanged(); + } catch (err) { + this.opts.warn?.( + `agent-team turn boundary handling failed for "${event.memberId}": ${err instanceof Error ? err.message : String(err)}` + ); + } + } + /** 持锁后装配:journal(store) → runtime → 恢复对账 → RPC server + 方法表。 */ + async serve() { + if (this.closed) throw new Error("host is closed"); + const paths = this.paths(); + const generationSignal = providerHasGeneration(this.provider) ? this.provider.activateGeneration() : void 0; + const ownerToken = this.lock.info?.token; + const ownsGeneration = () => !this.closed && ownerToken !== void 0 && this.lock.info?.token === ownerToken && !generationSignal?.aborted; + this.lock.startHeartbeat(); + let store; + try { + const journal = { + ...this.opts.journal, + maxLineBytes: Math.max( + this.opts.journal?.maxLineBytes ?? 65536, + this.limits.maxMessageBytes + 4096 + ) + }; + store = await JournalTeamStore.open(this.dataRoot, this.teamId, { + lock: this.lock, + journal + }); + } catch (err) { + if (!ownsGeneration()) return; + this.lock.stopHeartbeat(); + await this.lock.release(); + throw err; + } + if (!ownsGeneration()) { + await store.close({ checkpoint: false }); + return; + } + const runtime = new TeamRuntime({ + teamId: this.teamId, + store, + provider: this.provider, + limits: this.limits, + presentation: providerIsPresentation(this.provider) ? this.provider : void 0, + // stage-4:宿主内 Lead 无直达通道(D2)→ 投递走 hook 三通道 + 回执折叠。 + // 灰度唤醒:TEAM_WAKE_LEAD=1 且 Lead 空闲时拉起 --resume 回合;仍返回 false(未确认送达)。 + ...providerDeliversLeadViaHooks(this.provider) ? { + steerLead: () => { + if (providerWakesLead(this.provider)) { + void this.provider.wakeLead().then((result) => { + if (result.woke) { + this.opts.warn?.(`agent-team lead wake launched for team "${this.teamId}"`); + } else if (result.reason !== "disabled" && result.reason !== "lead-active" && result.reason !== "recent-activity" && result.reason !== "cooldown") { + this.opts.warn?.(`agent-team lead wake skipped for team "${this.teamId}": ${result.reason}`); + } + }).catch((err) => { + this.opts.warn?.( + `agent-team lead wake failed for team "${this.teamId}": ${err instanceof Error ? err.message : String(err)}` + ); + }); + } + return false; + } + } : {}, + warn: this.opts.warn, + ...generationSignal !== void 0 ? { signal: generationSignal } : {} + }); + if (providerHasBoundary(this.provider)) { + this.provider.bind({ + onBoundary: (event) => void this.handleTurnBoundary(event), + pendingLookup: (memberId) => { + const state = store.state(); + return runtime.mailbox.pendingFor(state, memberId).map((message) => ({ messageId: message.id, framedJson: JSON.stringify(frameMessage(message)) })); + }, + // 0.4.1:模型失败记录变化(后台续跑同步失败/恢复清除)→ 成员展示立即刷新 + // (Activity 唤醒 + 面板下一帧拿到新诊断;不等下一次轮次边界)。 + onModelFailureChanged: () => { + if (this.mode === "coordinator" && this.runtime !== null && !this.closed) { + this.runtime.roster.notifyStatusChanged(); + } + } + }); + const adopted = this.provider.adoptOrphans(); + this.opts.warn?.( + `agent-team coordinator adopted team "${this.teamId}": finalized ${adopted.finalized.length} finished turn(s), watching ${adopted.adopted.length} live turn(s)` + ); + } + this.initialLoad = store.lastLoad; + const initialState = store.state(); + if (initialState.failure !== void 0) { + this.degradedReason = initialState.failure; + this.opts.warn?.( + `Agent Teams coordinator for team "${this.teamId}" started in degraded mode (projection failure): ${initialState.failure}` + ); + } else { + try { + await runtime.recoverAll(); + } catch (err) { + if (ownsGeneration()) throw err; + runtime.close(); + await store.close({ checkpoint: false }); + return; + } + if (!ownsGeneration()) { + runtime.close(); + await store.close({ checkpoint: false }); + return; + } + if (providerHasBoundary(this.provider)) this.provider.startBackground?.(); + } + if (!ownsGeneration()) { + runtime.close(); + await store.close({ checkpoint: false }); + return; + } + const socket = resolveSocketPath(paths.teamDir); + const token = newRpcToken(); + const server2 = new RpcServer(socket.socketPath, { + token, + maxFrameBytes: frameBudgetFor(this.limits.maxMessageBytes) + }); + const table = buildTeamMethodTable({ + dataRoot: this.opts.dataRoot, + warn: this.opts.warn, + teamId: this.teamId, + runtime, + store, + coordinatorBootId: this.lock.info?.bootId ?? bootId() + }); + registerTeamMethods(server2, table); + try { + await server2.listen({ callTimeoutMs: this.opts.callTimeoutMs }); + } catch (err) { + if (ownsGeneration()) throw err; + runtime.close(); + await store.close({ checkpoint: false }); + return; + } + if (!ownsGeneration()) { + await server2.close(); + runtime.close(); + await store.close({ checkpoint: false }); + return; + } + writeRpcToken(paths.teamDir, token); + writeSocketRegistry(paths.teamDir, socket.socketPath); + this.store = store; + this.runtime = runtime; + this.server = server2; + this.table = table; + this.mode = "coordinator"; + this.stopWatcher(); + this.startDeliverySweep(); + this.opts.onPromoted?.({ + socketPath: socket.socketPath, + seq: store.committedSeq, + fromCheckpoint: this.initialLoad?.fromCheckpoint ?? false, + ...this.degradedReason !== void 0 ? { failure: this.degradedReason } : {} + }); + } + /** 单发晋升尝试:锁缺失/过龄才出手;新鲜持有 → false。 */ + async promoteOnce() { + if (this.mode === "coordinator" || this.closed) return this.mode === "coordinator"; + const observed = this.lock.observe(); + if (observed.exists && observed.ageMs <= this.lock.tuningOptions.expiryMs) { + return false; + } + try { + await this.lock.acquire({ waitMs: 0 }); + } catch { + return false; + } + await this.serve(); + return this.currentMode === "coordinator"; + } + startTakeoverWatcher() { + if (this.opts.autoTakeover === false || this.watcher !== null) return; + const pollMs = this.opts.takeoverPollMs ?? 100; + const watcher = setInterval(() => { + void this.tryPromote().catch(() => void 0); + }, pollMs); + watcher.unref?.(); + this.watcher = watcher; + } + stopWatcher() { + if (this.watcher !== null) { + clearInterval(this.watcher); + this.watcher = null; + } + } + /** + * pending 补投:轮次边界是主路径;进程瞬时失败(拉起后未落库即退出)会留下 pending, + * 若没有新的边界/发送就永远不会再试。这里按固定间隔扫描(provider 内部对运行中/退避 + * 目标快速返回 queued,不重复拉起)。 + */ + startDeliverySweep() { + if (this.deliveryTimer !== null) return; + const everyMs = this.opts.deliverySweepMs ?? 2e3; + if (everyMs <= 0) return; + this.deliveryTimer = setInterval(() => { + if (this.mode !== "coordinator" || this.runtime === null || this.closed) return; + try { + const state = this.store?.state(); + if (state === void 0) return; + const delivered = new Set(state.delivered); + if (!state.messages.some((message) => !delivered.has(message.id))) return; + } catch { + return; + } + void this.runtime.mailbox.recoverFor("all").catch((err) => { + this.opts.warn?.( + `agent-team delivery sweep failed for "${this.teamId}": ${err instanceof Error ? err.message : String(err)}` + ); + }); + }, everyMs); + this.deliveryTimer.unref?.(); + } + stopDeliverySweep() { + if (this.deliveryTimer !== null) { + clearInterval(this.deliveryTimer); + this.deliveryTimer = null; + } + } +}; +function providerIsPresentation(provider) { + return typeof provider.statusOf === "function" && typeof provider.modelOf === "function"; +} +function providerHasGeneration(provider) { + return typeof provider.activateGeneration === "function"; +} +function providerHasBoundary(provider) { + return typeof provider.bind === "function" && typeof provider.adoptOrphans === "function"; +} +function providerDeliversLeadViaHooks(provider) { + return provider.LEAD_DELIVERY_VIA_HOOKS === true; +} +function providerWakesLead(provider) { + return typeof provider.wakeLead === "function"; +} + +// src/mcp/backend.ts +var WAIT_PROGRESS_INTERVAL_MS = 9e3; +var WAIT_DEFAULT_TIMEOUT_MS = 3e4; +var DEFAULT_IDLE_RECLAIM_MS = 10 * 6e4; +var IDLE_SWEEP_MS = 6e4; +var TeamToolBackend = class { + constructor(opts) { + this.opts = opts; + this.now = opts.now ?? Date.now; + this.idleReclaimMs = opts.idleReclaimMs ?? DEFAULT_IDLE_RECLAIM_MS; + } + teams = /* @__PURE__ */ new Map(); + idleTimer = null; + now; + idleReclaimMs; + /** 〔对齐轮〕0.2.1 D3:interrupt 开关(默认 true)。 */ + get interruptEnabled() { + return this.opts.interrupt ?? true; + } + /** 冷启动即服务:惰性 open(并发共享同一 promise);失败不留半成品缓存。 */ + backendFor(teamId) { + let entry = this.teams.get(teamId); + if (entry === void 0) { + const provider = this.opts.providerFactory !== void 0 ? this.opts.providerFactory(teamId) : this.opts.provider !== void 0 ? this.opts.provider : void 0; + const resolvedProvider = provider; + const opening = TeamCoordinatorHost.open({ + dataRoot: this.opts.dataRoot, + teamId, + limits: this.opts.limits, + ...provider !== void 0 ? { provider } : {}, + warn: this.opts.warn + }); + entry = { + host: null, + opening, + // 缺省装配(host 内部 new MockProvider)时拿不到实例 → 模型消歧退化为「按目录唯一命中」。 + ...resolvedProvider !== void 0 ? { provider: resolvedProvider } : {}, + lastUsedAt: this.now(), + inflight: 0 + }; + const self = entry; + void opening.then( + (host) => { + self.host = host; + return host; + }, + (err) => { + if (this.teams.get(teamId) === self) this.teams.delete(teamId); + this.opts.warn?.(`agent-team host open failed for "${teamId}": ${err instanceof Error ? err.message : String(err)}`); + return void 0; + } + ); + this.teams.set(teamId, entry); + this.ensureIdleSweep(); + } + entry.lastUsedAt = this.now(); + return entry.opening; + } + /** 用法包装:记录在途/最后使用时间;工具方法统一经此取 host。 */ + async withHost(teamId, fn) { + const host = await this.backendFor(teamId); + const entry = this.teams.get(teamId); + if (entry !== void 0) entry.inflight += 1; + try { + return await fn(host); + } finally { + if (entry !== void 0) { + entry.inflight -= 1; + entry.lastUsedAt = this.now(); + } + } + } + /** 空闲回收:关闭超过阈值且无在途调用的团队 host(durable 日志保留,下次调用按冷启动恢复)。 */ + async sweepIdleHosts() { + if (this.idleReclaimMs <= 0) return 0; + const now2 = this.now(); + let reclaimed = 0; + for (const [teamId, entry] of [...this.teams.entries()]) { + if (entry.host === null || entry.inflight > 0) continue; + if (now2 - entry.lastUsedAt < this.idleReclaimMs) continue; + this.teams.delete(teamId); + const host = entry.host; + try { + await host.close(); + reclaimed += 1; + } catch (err) { + this.opts.warn?.( + `agent-team idle host close failed for "${teamId}": ${err instanceof Error ? err.message : String(err)}` + ); + } + } + if (reclaimed > 0) this.opts.warn?.(`agent-team reclaimed ${reclaimed} idle team host(s)`); + return reclaimed; + } + ensureIdleSweep() { + if (this.idleTimer !== null || this.idleReclaimMs <= 0) return; + this.idleTimer = setInterval(() => void this.sweepIdleHosts(), IDLE_SWEEP_MS); + this.idleTimer.unref?.(); + } + /** 诊断:某团队 host 是否已开且为协调者(契约测试用)。 */ + modeOf(teamId) { + const entry = this.teams.get(teamId); + return entry?.host?.currentMode ?? "unopened"; + } + async close() { + if (this.idleTimer !== null) { + clearInterval(this.idleTimer); + this.idleTimer = null; + } + const entries = [...this.teams.values()]; + this.teams.clear(); + const errors = []; + for (const entry of entries) { + try { + const host = await entry.opening; + await host.close(); + } catch (err) { + errors.push(err); + } + } + if (errors.length > 0) { + throw new AggregateError(errors, "Agent Teams tool backend close failed"); + } + } + // ---------------------------------------------------------------- 9 工具操作 + /** spawn_teammate(02 §9.3;context 缺省 fresh 由域层承担;〔对齐轮〕0.2.1:初始任务不含身份前缀)。 + * 参数原值直传——类型/枚举守卫在方法表 requireString/optionalString(冻结消息)。 + * 0.4.0:model/thoughtLevel 参数注销——成员模型唯一路线 = provider 每轮跟随 Lead 最新 + * 已确认选择;Lead 模型不可继承(官方套餐/目录外/解析不出)时 provider 抛错 → 本调用报错。 */ + async spawnTeammate(identity, args) { + const requestId = crypto.randomUUID(); + try { + return await this.withHost( + identity.teamId, + async (host) => await host.dispatch("member.spawn", { + session_id: identity.agentId, + name: args.name, + description: args.description, + prompt: args.prompt, + requestId, + ...args.context !== void 0 ? { context: args.context } : {} + }) + ); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + if (!/rpc connection closed|rpc (?:method|call) member\.spawn timed out|coordinator is unavailable/.test(message)) throw err; + const host = await this.backendFor(identity.teamId); + const provider = host.providerForRead; + const registered = provider?.requestStatus?.(requestId); + if (registered === void 0) { + throw new Error("\u6210\u5458\u521B\u5EFA\u8BF7\u6C42\u7ED3\u679C\u672A\u786E\u8BA4\uFF0C\u65E0\u6CD5\u5173\u8054\u539F\u767B\u8BB0\uFF1B\u4E0D\u4F1A\u81EA\u52A8\u91CD\u653E"); + } + const rows = await this.memberRows(host, identity); + const member = rows.find((row) => row.target === args.name); + if (member === void 0) throw new Error("\u539F\u521B\u5EFA\u8BF7\u6C42\u5DF2\u767B\u8BB0\uFF0C\u4F46\u6210\u5458\u72B6\u6001\u6682\u4E0D\u53EF\u8BFB"); + return member.status === "provisioning" ? { member, creation: "pending", message: "\u7ED3\u679C\u5F85\u786E\u8BA4" } : { member }; + } + } + // 0.4.0 注销 setMemberModel / resolveModelArgs / leadProviderId / catalog / wireModelSelection / + // validateThoughtLevel(成员模型没有独立配置通道;stage-8 原文见 traceability §18 与 git 历史)。 + /** list_agents 的行派生(协调者 = roster 全保真;代理 = 本地重放派生)。 */ + async memberRows(host, identity) { + const runtime = host.teamRuntime; + if (runtime !== null) { + return runtime.roster.listMembers(identity.agentId).members; + } + const loaded = await host.readBoard(); + requireMembership( + () => { + if (loaded.state.failure !== void 0) throw new Error(loaded.state.failure); + return loaded.state; + }, + identity.agentId + ); + return memberRowsFromState(loaded.state.id, loaded.state.members, identity.agentId); + } + /** send_message(02 §9.5;内容映射 content=[{type:"text",text:message}],target 原值直传)。 + * 〔对齐轮〕0.2.1:工具层输出 {sent:true}(不暴露 messageId;投递状态为内部适配层)。 */ + async sendMessage(identity, args) { + const content = [{ type: "text", text: args.message }]; + return this.withHost(identity.teamId, async (host) => { + await host.dispatch("message.send", { + session_id: identity.agentId, + targetName: args.target, + content + }); + return { sent: true }; + }); + } + /** list_agents(02 §9.6;输出 MEMBER_VIEW[],Lead 伪行 target="lead")。 */ + async listAgents(identity) { + return this.withHost(identity.teamId, (host) => this.memberRows(host, identity)); + } + /** interrupt_agent(02 §9.8;Lead-only 域层校验,工具层不放宽;target 原值直传)。 + * 〔对齐轮〕0.2.1 D3:interrupt=false 时本工具未注册——调用按「未知工具」拒绝(handlers 承担)。 */ + async interruptAgent(identity, args) { + return this.withHost( + identity.teamId, + async (host) => await host.dispatch("member.interrupt", { + session_id: identity.agentId, + name: args.target + }) + ); + } + /** + * wait_agent(02 §9.7/§8):缺省 30000 → 非法值绕过捷径直报 TEAM_INVALID_TIMEOUT + * → 合法则先跑 no-active-peer 捷径(仅协调者模式可评估)→ 否则注册等待 + * (等待期 progress 保活 ≤10s;代理模式经 socket 且按调用豁免超时)。 + */ + async waitAgent(identity, args, emitProgress, signal) { + const raw = args.timeout_ms; + const timeoutMs = raw === void 0 ? WAIT_DEFAULT_TIMEOUT_MS : raw; + return this.withHost(identity.teamId, async (host) => { + if (!isValidTimeout(timeoutMs)) { + if (typeof timeoutMs === "number") { + return await host.dispatch( + "wait.agent", + { session_id: identity.agentId, timeoutMs }, + signal !== void 0 ? { signal } : {} + ); + } + throw new TeamError( + "TEAM_INVALID_TIMEOUT", + "timeoutMs must be an integer from 10000 through 3600000" + ); + } + const runtime = host.teamRuntime; + let wait; + if (runtime !== null) { + wait = host.dispatch( + "wait.agent", + { session_id: identity.agentId, timeoutMs }, + signal !== void 0 ? { signal } : {} + ); + } else { + const { teamDir } = teamPaths(this.opts.dataRoot, identity.teamId); + wait = callCoordinator( + teamDir, + identity.teamId, + "wait.agent", + { session_id: identity.agentId, timeoutMs }, + { + timeoutMs: timeoutMs + WAIT_AGENT_GRACE_MS, + ...signal !== void 0 ? { signal } : {} + } + ); + } + return emitProgress === void 0 ? wait : withKeepAlive(wait, emitProgress); + }); + } + /** team_task_create(02 §9.9;snake_case → 方法表参数,原值直传)。 */ + async taskCreate(identity, args) { + return this.withHost(identity.teamId, async (host) => { + const result = await host.dispatch("task.create", { + session_id: identity.agentId, + subject: args.subject, + description: args.description, + ...args.blocked_by !== void 0 ? { blockedBy: args.blocked_by } : {}, + ...args.write_scopes !== void 0 ? { writeScopes: args.write_scopes } : {} + }); + return result.task; + }); + } + /** team_task_list(02 §9.10;过滤/分页语义与越界消息逐字由域层承担;类型守卫在 handlers)。 */ + async taskList(identity, args) { + return this.withHost( + identity.teamId, + async (host) => await host.dispatch("task.list", { + session_id: identity.agentId, + ...args.status !== void 0 ? { status: args.status } : {}, + ...args.owner !== void 0 ? { owner: args.owner } : {}, + ...args.ready !== void 0 ? { ready: args.ready } : {}, + ...args.cursor !== void 0 ? { cursor: args.cursor } : {}, + ...args.limit !== void 0 ? { limit: args.limit } : {} + }) + ); + } + /** team_task_get(02 §9.11;含 deleted 墓碑)。 */ + async taskGet(identity, args) { + return this.withHost(identity.teamId, async (host) => { + const result = await host.dispatch("task.get", { + session_id: identity.agentId, + taskId: args.task_id + }); + return result.task; + }); + } + /** team_task_update(02 §9.12;CAS 直传,原值交方法表校验)。 */ + async taskUpdate(identity, args) { + return this.withHost(identity.teamId, async (host) => { + const result = await host.dispatch("task.update", { + session_id: identity.agentId, + taskId: args.task_id, + expectedRevision: args.expected_revision, + action: args.action, + ...args.subject !== void 0 ? { subject: args.subject } : {}, + ...args.description !== void 0 ? { description: args.description } : {}, + ...args.blocked_by !== void 0 ? { blockedBy: args.blocked_by } : {}, + ...args.write_scopes !== void 0 ? { writeScopes: args.write_scopes } : {}, + ...args.owner !== void 0 ? { owner: args.owner } : {} + }); + return result.task; + }); + } + /** + * teammate 启动参数接口(T3.4;实参注入归 stage-4 provider)。 + * D6 对齐:--disallowed-tools Task(遮蔽一次性子代理工具,本阶段只留接口)。 + */ + static teammateDisallowedTools() { + return ["Task"]; + } +}; +var MEMBER_STATUS_BY_PHASE = { + active: "inactive", + provisioning: "provisioning", + failed: "failed" +}; +function memberRowsFromState(teamId, members, callerId) { + const rows = [ + { target: "lead", role: "lead", status: teamId === callerId ? "running" : "inactive", diagnostics: [] } + ]; + for (const member of members) { + rows.push({ + target: member.name, + role: "teammate", + status: MEMBER_STATUS_BY_PHASE[member.phase], + description: member.description, + provider: member.provider, + context: member.context, + diagnostics: member.error !== void 0 ? [member.error] : [] + }); + } + return rows; +} +async function withKeepAlive(wait, emitProgress, intervalMs = WAIT_PROGRESS_INTERVAL_MS) { + let tick = 0; + const timer = setInterval(() => { + tick += 1; + void emitProgress(tick, "waiting for team activity").catch(() => void 0); + }, intervalMs); + try { + return await wait; + } finally { + clearInterval(timer); + } +} + +// src/mcp/tools.ts +var PANEL_RESOURCE_URI = "ui://agent-team/team-panel.html"; +var PANEL_SURFACE_ID = "agent-team-panel"; +var TEAM_TOOL_DEFINITIONS = [ + { + // 02 §9.3(〔issue #9 D28〕去档位措辞;〔issue #5 / D29〕补不可继承失败口径) + name: "spawn_teammate", + description: "Create one named, durable teammate. Only the Team Lead may call this tool. Create teammates when the goal clearly benefits from delegation \u2014 multiple roles in parallel, disjoint write scopes, or long tasks needing their own context \u2014 within the member limit. A creation=pending response means the request is registered but its result is not confirmed; the member remains provisioning and is not ready for work. Observe that same member with list_agents/wait_agent instead of spawning another. If the Lead's model cannot be inherited (official plan model), the call fails \u2014 handle the work directly instead. The teammate automatically follows the Lead's latest confirmed model and reasoning level on every turn; there is no per-member model option.", + inputSchema: { + type: "object", + properties: { + name: { type: "string", description: "Unique lower-kebab-case teammate name." }, + description: { type: "string", description: "Short description of the delegated responsibility." }, + prompt: { type: "string", description: "Bootstrap instructions with a shared task id; get and claim that task before working. Report blockers when not ready." }, + context: { + type: "string", + enum: ["fresh", "fork"], + description: "fresh starts without Lead history; fork inherits completed Lead turns. Defaults to fresh." + } + }, + required: ["name", "description", "prompt"], + additionalProperties: false + }, + _meta: { + ui: { resourceUri: PANEL_RESOURCE_URI, surface: PANEL_SURFACE_ID } + } + }, + { + // 02 §9.5(〔对齐轮〕0.2.1 描述:删 "durable"、"durable message"→"message") + name: "send_message", + description: "Send one message to another Team member. Running teammates receive it at a turn boundary; inactive teammates resume. The Lead reads messages through wait_agent.", + inputSchema: { + type: "object", + properties: { + target: { + type: "string", + description: "Member target returned by spawn_teammate or list_agents, including lead." + }, + message: { type: "string", description: "Self-contained message for the target." } + }, + required: ["target", "message"], + additionalProperties: false + } + }, + { + // 02 §9.6 + name: "list_agents", + description: "List the Lead and every durable teammate with an addressable target and current availability. inactive means no turn is executing, not a task result. provisioning and failed describe member creation.", + inputSchema: { + type: "object", + properties: {}, + additionalProperties: false + } + }, + { + // 02 §9.8 + name: "interrupt_agent", + description: "Interrupt one teammate's current turn while preserving its pending inbox. Team Lead only.", + inputSchema: { + type: "object", + properties: { + target: { + type: "string", + description: "Teammate target returned by spawn_teammate or list_agents." + } + }, + required: ["target"], + additionalProperties: false + } + }, + // 0.4.0 注销 member_set_model(02 §9.13):成员模型没有独立配置通道,唯一路线 = 每轮 + // 跟随 Lead 最新已确认选择;原规格条目见 traceability §18 与 git 历史。 + { + // 02 §9.7(〔对齐轮〕0.2.1 描述:"mailbox"→"message") + name: "wait_agent", + description: "Receive pending Lead inbox messages immediately, even if teammates are inactive; otherwise wait for the next Team change. This never wakes inactive members and returns noProgress immediately when no peer can progress and no messages await. Read returned messages before follow-ups. Re-list after wakeup or timeout.", + inputSchema: { + type: "object", + properties: { + timeout_ms: { + type: "integer", + description: "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." + } + }, + additionalProperties: false + } + }, + { + // 02 §9.9 + name: "team_task_create", + description: "Create one unowned pending task on the shared Team task board.", + inputSchema: { + type: "object", + properties: { + subject: { type: "string", description: "Concise task title." }, + description: { type: "string", description: "Complete task details and acceptance criteria." }, + blocked_by: { type: "array", items: { type: "string" }, description: "Task ids that must complete first." }, + write_scopes: { + type: "array", + items: { type: "string" }, + description: "Advisory workspace-relative file or directory prefixes this task expects to modify." + } + }, + required: ["subject", "description"], + additionalProperties: false + } + }, + { + // 02 §9.10 + name: "team_task_list", + description: "List shared tasks, including readiness, owner, revision, blockers, and write-scope warnings.", + inputSchema: { + type: "object", + properties: { + status: { + type: "string", + enum: ["pending", "in_progress", "completed"], + description: "Optional exact status filter." + }, + owner: { + type: "string", + description: "Optional member target from spawn_teammate or list_agents, matching ownerName; use unowned for tasks without an owner." + }, + ready: { type: "boolean", description: "Optional readiness filter." }, + cursor: { type: "integer", description: "Zero-based result offset. Defaults to 0." }, + limit: { type: "integer", description: "Number of rows, 1 through 100. Defaults to 50." } + }, + additionalProperties: false + } + }, + { + // 02 §9.11 + name: "team_task_get", + description: "Read the complete latest value of one shared task before changing or executing it.", + inputSchema: { + type: "object", + properties: { + task_id: { type: "string", description: "Shared task id." } + }, + required: ["task_id"], + additionalProperties: false + } + }, + { + // 02 §9.12(〔issue #9 三档化 D28〕描述去 orchestrator 档位措辞) + name: "team_task_update", + description: "Compare-and-set a shared task action using the latest revision from team_task_get or team_task_list. When the Lead verifies a completed task, reopen it with concrete findings on failure.", + inputSchema: { + type: "object", + properties: { + task_id: { type: "string", description: "Shared task id." }, + expected_revision: { + type: "integer", + description: "Current task revision used as the CAS precondition." + }, + action: { + type: "string", + enum: ["claim", "release", "edit", "set_dependencies", "complete", "reopen", "reassign", "delete"], + description: "Task transition to apply." + }, + subject: { type: "string", description: "Replacement title for edit." }, + description: { + type: "string", + description: "Replacement details for edit; for reopen, the concrete findings that failed verification." + }, + blocked_by: { + type: "array", + items: { type: "string" }, + description: "Complete blocker list for set_dependencies." + }, + write_scopes: { + type: "array", + items: { type: "string" }, + description: "Replacement advisory write scopes for edit." + }, + owner: { + type: "string", + description: "Member target from spawn_teammate or list_agents for Lead-only reassign; omit to unassign." + } + }, + required: ["task_id", "expected_revision", "action"], + additionalProperties: false + } + } +]; +var TEAM_TOOL_NAMES = new Set(TEAM_TOOL_DEFINITIONS.map((t) => t.name)); +function teamToolDefinitions(options = {}) { + if (options.leadMode === "off") return []; + const interrupt = options.interrupt ?? true; + return interrupt ? TEAM_TOOL_DEFINITIONS : TEAM_TOOL_DEFINITIONS.filter((t) => t.name !== "interrupt_agent"); +} + +// src/mcp/policy.ts +function teamPolicy(interrupt) { + return `Agent Teams is available in this session + +The Team Lead and all teammates share the same working directory and filesystem. Edits are immediately visible to every member. Split write work into disjoint scopes, record expected write scopes on shared tasks, and use task dependencies when work must be ordered. Write-scope overlap is advisory, not a lock. + +Prefer read/edit/write for file changes. If a file operation reports that the file changed since you last read it, read the current file again, rebase your intended change onto the new content, and retry. Bash, formatters, code generators, and scripts are not fully protected by the filesystem version guard; coordinate them explicitly and have the Lead review the final diff and run tests. + +Use the target returned by spawn_teammate or list_agents for send_message${interrupt ? " and interrupt_agent" : ""}, or as owner when assigning or filtering shared tasks. send_message queues delivery to a running teammate's next turn boundary and starts or resumes an inactive teammate. The Lead receives queued messages through wait_agent during its current turn, with session hooks as a fallback. inactive means no turn is executing; it does not describe task completion, success, failure, or waiting for other agents. provisioning means member creation is in progress; failed means member creation failed. A peer message starts with its sender name. A successful send does not mean the recipient has processed it. Each delegated unit needs a shared task with acceptance criteria. Create it before dispatching the work; the teammate must list/get it, claim with the current revision, perform the work, then complete and report to the Lead. An initial prompt or an output file is not a task-board record. Task readiness never starts an owner. Use wait_agent to receive pending Lead inbox messages before sending follow-ups, even when teammates are inactive. With no pending messages, it waits for new changes and returns noProgress immediately when no other member can produce a change; it never wakes a member. Consume returned messages, then recheck shared tasks before deciding whether more work or another message is needed. Re-list after wakeup or timeout. The Lead must wait for required teammates before giving the final answer.`; +} +var POLICY_TEXT = teamPolicy(true); +var HOOK_POLICY_PREFIX = "[agent-team]"; +var IDENTITY_LEAD_TEXT = `You are the Team Lead named "lead". +Use list_agents({}) to find your teammates and their names. +To message another teammate, use send_message({ target: "", message: "..." }).`; +var POLICY_PROBE_MARKER = "quartz-ember-73"; +var ON_DEMAND_SECTION_TEXT = "Lead operating mode (on-demand): Judge each request by delegation value before using the team. Handle work directly yourself \u2014 with a one-line reason, no forced tasks \u2014 for questions and explanations, small changes confined to a single file, read-only research summaries, or when every teammate is busy and the request is unrelated to existing work. Use the team workflow when work clearly benefits from multiple roles in parallel, when write scopes must be split across members, when a long task deserves its own context, or when the user explicitly names members. When you delegate, turn each delegated unit into a shared task whose description states concrete acceptance criteria, assign an owner, record expected write scopes, and set dependencies when ordering matters. Require each owner to self-check and report changed files and test results before completing. When a task reaches completed, verify it independently: review the final diff and run the relevant tests yourself; if it fails, reopen the task with concrete findings; if it passes, append your acceptance verdict to the task description \u2014 a task is done when completed plus your recorded acceptance. Reuse idle teammates before spawning new ones and keep one member per role, within the member limit. Wait for required teammates and synthesize their results for the final answer."; +var FIRST_SPAWN_NOTE = `[agent-team] Team mode is now active: this is the first teammate of this session. +${ON_DEMAND_SECTION_TEXT}`; +function buildSessionStartContext(identityText, interrupt = true, modeSection) { + const policy = teamPolicy(interrupt); + const section = modeSection !== void 0 ? ` +${HOOK_POLICY_PREFIX} ${modeSection}` : ""; + const probe = process.env.TEAM_POLICY_PROBE === "1" ? ` +${HOOK_POLICY_PREFIX} \u7B56\u7565\u6CE8\u5165\u9A8C\u8BC1\u6807\u8BB0\uFF1A${POLICY_PROBE_MARKER}` : ""; + return `${HOOK_POLICY_PREFIX} ${policy} +${HOOK_POLICY_PREFIX} ${identityText}${section}${probe}`; +} +var SESSION_START_CONTEXT = buildSessionStartContext(IDENTITY_LEAD_TEXT, true); +var FAIL_LOUD_WARNING = "[agent-team] \u8B66\u544A\uFF1A\u672A\u68C0\u6D4B\u5230\u672C\u4F1A\u8BDD\u7684\u7B56\u7565\u6CE8\u5165\uFF08SessionStart hook \u53EF\u80FD\u672A\u751F\u6548\uFF09\u3002\u8BF7\u786E\u8BA4\u63D2\u4EF6\u5DF2\u542F\u7528\u4E14 hooks \u58F0\u660E\u5B58\u5728\uFF1B\u56E2\u961F\u5DE5\u5177\u4ECD\u53EF\u8C03\u7528\uFF0C\u4F46\u6A21\u578B\u53EF\u80FD\u672A\u52A0\u8F7D\u5B8C\u6574\u534F\u4F5C\u7B56\u7565\u3002"; + +// src/mcp/results.ts +function compactJson(value) { + return JSON.stringify(value); +} +function successResult(value) { + return { content: [{ type: "text", text: compactJson(value) }] }; +} +function errorResult(err) { + const body = normalizeError(err); + return { + isError: true, + content: [{ type: "text", text: compactJson({ error: body }) }] + }; +} +function normalizeError(err) { + if (isTeamError(err)) return { code: err.code, message: err.message }; + if (err instanceof AggregateError) { + const first = err.errors.find(isTeamError); + if (first !== void 0) { + return { code: first.code, message: `${err.message}: ${first.message}` }; + } + const firstPlain = err.errors[0]; + return { + message: err.message + (firstPlain !== void 0 ? `: ${firstPlain instanceof Error ? firstPlain.message : String(firstPlain)}` : "") + }; + } + return { message: err instanceof Error ? err.message : String(err) }; +} +function withFailLoud(result, identity) { + if (identity.hookRegistered) return result; + return { ...result, content: [...result.content, { type: "text", text: FAIL_LOUD_WARNING }] }; +} + +// src/mcp/identity.ts +import fs10 from "node:fs"; +import path9 from "node:path"; +function sessionMapPath(dataRoot) { + return path9.join(dataRoot, "session-map.json"); +} +function safeSessionKey(sessionId) { + return sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128); +} +function registryLockPath(dataRoot) { + return `${sessionMapPath(dataRoot)}.lock`; +} +function withRegistryLock(dataRoot, fn) { + const lock = registryLockPath(dataRoot); + const started = Date.now(); + let fd = null; + while (Date.now() - started < 2e3) { + try { + fd = fs10.openSync(lock, "wx", 384); + break; + } catch { + try { + const stat = fs10.statSync(lock); + if (Date.now() - stat.mtimeMs > 5e3) fs10.unlinkSync(lock); + } catch { + } + const until = Date.now() + 20; + while (Date.now() < until) { + } + } + } + try { + fn(); + } finally { + if (fd !== null) { + try { + fs10.closeSync(fd); + fs10.unlinkSync(lock); + } catch { + } + } + } +} +function readSessionRegistry(dataRoot) { + try { + const parsed = JSON.parse(fs10.readFileSync(sessionMapPath(dataRoot), "utf8")); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return parsed; + } catch { + return {}; + } +} +function upsertSessionEntry(dataRoot, sessionId, patch) { + const file = sessionMapPath(dataRoot); + try { + fs10.mkdirSync(path9.dirname(file), { recursive: true }); + withRegistryLock(dataRoot, () => { + let registry2 = {}; + try { + const parsed = JSON.parse(fs10.readFileSync(file, "utf8")); + if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) { + registry2 = parsed; + } + } catch (err) { + if (err.code !== "ENOENT") { + try { + fs10.renameSync(file, `${file}.corrupt-${Date.now()}`); + } catch { + } + } + } + const key = safeSessionKey(sessionId); + const prior = registry2[key] ?? {}; + registry2[key] = { ...prior, ...patch, session_id: sessionId }; + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const fd = fs10.openSync(tmp, "w", 384); + try { + fs10.writeFileSync(fd, JSON.stringify(registry2, null, 2)); + fs10.fsyncSync(fd); + } finally { + fs10.closeSync(fd); + } + fs10.renameSync(tmp, file); + }); + } catch { + } +} +function resolveIdentity(opts) { + const metaSession = opts.meta?.session_id; + let sessionId; + let source = "meta"; + if (typeof metaSession === "string" && metaSession.length > 0) { + sessionId = metaSession; + } else { + const windowMs = opts.fallbackWindowMs ?? 3e5; + const candidates = []; + for (const entry2 of Object.values(readSessionRegistry(opts.dataRoot))) { + if (typeof entry2?.session_id !== "string") continue; + const firstSeen = entry2.firstSeen !== void 0 ? Date.parse(entry2.firstSeen) : NaN; + if (Number.isNaN(firstSeen)) continue; + if (Math.abs(firstSeen - opts.bootTimeMs) <= windowMs) candidates.push(entry2); + } + if (candidates.length === 1) { + sessionId = candidates[0].session_id; + source = "hook-map"; + } + } + if (sessionId === void 0) { + throw notMemberError(""); + } + const registry2 = readSessionRegistry(opts.dataRoot); + const entry = registry2[safeSessionKey(sessionId)] ?? {}; + const runtimeScope = opts.meta?.runtime_scope; + const hookRegistered = entry.hookRegistered === true; + if (entry.role === "teammate" && typeof entry.teamId === "string" && entry.teamId.length > 0) { + touch(opts, sessionId, entry, source); + const memberId = typeof entry.memberId === "string" && entry.memberId.length > 0 ? entry.memberId : sessionId; + return { + sessionId, + teamId: entry.teamId, + role: "teammate", + name: typeof entry.name === "string" && entry.name.length > 0 ? entry.name : sessionId, + agentId: memberId, + source, + hookRegistered + }; + } + if (runtimeScope === "subagent") { + throw notMemberError(sessionId); + } + touch(opts, sessionId, entry, source); + return { + sessionId, + teamId: sessionId, + role: "lead", + name: "lead", + agentId: sessionId, + source, + hookRegistered + }; +} +function notMemberError(agentId) { + return new TeamError( + "TEAM_NOT_MEMBER", + `agent "${agentId}" is not a member of an active Agent Team` + ); +} +function touch(opts, sessionId, entry, source) { + const patch = { + lastSeen: ts(), + ...entry.firstSeen === void 0 ? { firstSeen: ts() } : {}, + ...entry.hookRegistered === true ? { hookRegistered: true } : {} + }; + if (entry.session_id === void 0 || source === "hook-map") patch.session_id = sessionId; + upsertSessionEntry(opts.dataRoot, sessionId, patch); +} + +// src/mcp/handlers.ts +async function handleTeamToolCall(opts, tool) { + if (opts.leadMode === "off") { + return errorResult( + new TypeError(`unsupported team tool: ${tool} (leadMode "off" \u2014 Agent Teams disabled)`) + ); + } + let identity; + try { + identity = resolveIdentity({ + dataRoot: opts.dataRoot, + meta: opts.meta, + bootTimeMs: opts.bootTimeMs, + ...opts.now !== void 0 ? { now: opts.now } : {} + }); + } catch (err) { + return errorResult(err); + } + const probeFirstSpawn = opts.leadMode === "auto" && tool === "spawn_teammate" && !teamEverCreated(teamPaths(opts.dataRoot, identity.teamId).teamDir, identity.teamId); + try { + const result = await dispatch(opts, identity, tool); + const success = withFailLoud(successResult(result), identity); + return probeFirstSpawn ? { ...success, content: [...success.content, { type: "text", text: FIRST_SPAWN_NOTE }] } : success; + } catch (err) { + return withFailLoud(errorResult(err), identity); + } +} +async function dispatch(opts, identity, tool) { + const { backend: backend2, args } = opts; + switch (tool) { + case "spawn_teammate": + return backend2.spawnTeammate(identity, { + name: args.name, + description: args.description, + prompt: args.prompt, + ...args.context !== void 0 ? { context: args.context } : {} + }); + case "send_message": + guardNonEmptyString(args.message, "message"); + return backend2.sendMessage(identity, { target: args.target, message: args.message }); + case "list_agents": + return backend2.listAgents(identity); + case "interrupt_agent": + if (!backend2.interruptEnabled) throw new TypeError("unsupported team tool: interrupt_agent"); + return backend2.interruptAgent(identity, { target: args.target }); + // 0.4.0 注销 member_set_model case(工具面 9 个;未知工具由上游分派拒绝)。 + case "wait_agent": + return backend2.waitAgent( + identity, + { ...args.timeout_ms !== void 0 ? { timeout_ms: args.timeout_ms } : {} }, + opts.emitProgress, + opts.signal + ); + case "team_task_create": + return backend2.taskCreate(identity, { + subject: args.subject, + description: args.description, + ...args.blocked_by !== void 0 ? { blocked_by: args.blocked_by } : {}, + ...args.write_scopes !== void 0 ? { write_scopes: args.write_scopes } : {} + }); + case "team_task_list": + if (args.ready !== void 0 && typeof args.ready !== "boolean") { + throw invalidArg('param "ready" must be a boolean'); + } + if (args.cursor !== void 0) guardSafeInteger(args.cursor, "cursor"); + if (args.limit !== void 0) guardSafeInteger(args.limit, "limit"); + if (args.status !== void 0 && args.status !== "pending" && args.status !== "in_progress" && args.status !== "completed") { + throw invalidArg('param "status" must be one of pending, in_progress, completed'); + } + return backend2.taskList(identity, { + ...args.status !== void 0 ? { status: args.status } : {}, + ...args.owner !== void 0 ? { owner: args.owner } : {}, + ...args.ready !== void 0 ? { ready: args.ready } : {}, + ...args.cursor !== void 0 ? { cursor: args.cursor } : {}, + ...args.limit !== void 0 ? { limit: args.limit } : {} + }); + case "team_task_get": + return backend2.taskGet(identity, { task_id: args.task_id }); + case "team_task_update": + return backend2.taskUpdate(identity, { + task_id: args.task_id, + expected_revision: args.expected_revision, + action: args.action, + ...args.subject !== void 0 ? { subject: args.subject } : {}, + ...args.description !== void 0 ? { description: args.description } : {}, + ...args.blocked_by !== void 0 ? { blocked_by: args.blocked_by } : {}, + ...args.write_scopes !== void 0 ? { write_scopes: args.write_scopes } : {}, + ...args.owner !== void 0 ? { owner: args.owner } : {} + }); + default: + throw new TypeError(`unsupported team tool: ${tool}`); + } +} +function invalidArg(message) { + return new TeamError("TEAM_INVALID_ARGUMENT", message); +} +function guardNonEmptyString(v, key) { + if (typeof v !== "string" || v.length === 0) { + throw invalidArg(`param "${key}" must be a non-empty string`); + } +} +function guardSafeInteger(v, key) { + if (typeof v !== "number" || !Number.isSafeInteger(v)) { + throw invalidArg(`param "${key}" must be a safe integer`); + } +} +function isTeamTool(name) { + return TEAM_TOOL_NAMES.has(name); +} + +// src/mcp/registry.ts +function listTeamTools(options = {}) { + return teamToolDefinitions(options).map((t) => ({ + name: t.name, + description: t.description, + inputSchema: t.inputSchema, + ...t._meta !== void 0 ? { _meta: t._meta } : {} + })); +} +async function callTeamTool(input, notifier) { + const emitProgress = buildProgressSink(input, notifier); + return handleTeamToolCall( + { + backend: input.backend, + dataRoot: input.dataRoot, + bootTimeMs: input.bootTimeMs, + meta: input.meta, + args: input.args, + ...input.leadMode !== void 0 ? { leadMode: input.leadMode } : {}, + ...emitProgress !== void 0 ? { emitProgress } : {}, + ...input.signal !== void 0 ? { signal: input.signal } : {}, + ...input.now !== void 0 ? { now: input.now } : {} + }, + input.name + ); +} +function buildProgressSink(input, notifier) { + if (input.name !== "wait_agent") return void 0; + const token = input.meta?.progressToken; + if (notifier === void 0 || token === void 0) return void 0; + if (typeof token !== "string" && typeof token !== "number") return void 0; + return async (progress, message) => { + try { + await notifier.sendNotification({ + method: "notifications/progress", + params: { + progressToken: token, + progress, + ...message !== void 0 ? { message } : {} + } + }); + } catch { + } + }; +} + +// src/provider/resume-provider.ts +import { createHash as createHash2 } from "node:crypto"; +import fs18 from "node:fs"; +import path17 from "node:path"; + +// src/provider/lead-wake.ts +import fs11 from "node:fs"; +import path10 from "node:path"; +var WAKE_COOLDOWN_MS = 3e4; +var WAKE_LOCK_STALE_MS = 12e4; +var WAKE_PROMPT = "[agent-team] \u4F60\u6709\u5F85\u6536\u56E2\u961F\u6D88\u606F\u3002\u8BF7\u53EA\u5904\u7406\u6536\u4EF6\u7BB1\uFF08\u8BFB\u53D6\u5E76\u56DE\u590D\u6458\u8981\uFF09\uFF0C\u4E0D\u8981\u6267\u884C\u5176\u4ED6\u4EFB\u52A1\u3002"; +function leadDir(teamDir) { + return path10.join(teamDir, "lead"); +} +function leadStatePath(teamDir) { + return path10.join(leadDir(teamDir), "state.json"); +} +function wakeLockPath(teamDir) { + return path10.join(leadDir(teamDir), "wake.lock"); +} +function readLeadState(teamDir) { + try { + const parsed = JSON.parse(fs11.readFileSync(leadStatePath(teamDir), "utf8")); + if (typeof parsed.active !== "boolean" || typeof parsed.updatedAt !== "string") return void 0; + return parsed; + } catch { + return void 0; + } +} +function writeLeadState(teamDir, state) { + const dir = leadDir(teamDir); + fs11.mkdirSync(dir, { recursive: true }); + const file = leadStatePath(teamDir); + const tmp = `${file}.tmp-${process.pid}`; + const fd = fs11.openSync(tmp, "w", 384); + try { + fs11.writeFileSync(fd, JSON.stringify(state, null, 2)); + fs11.fsyncSync(fd); + } finally { + fs11.closeSync(fd); + } + fs11.renameSync(tmp, file); +} +function acquireLock(teamDir, now2) { + const dir = leadDir(teamDir); + fs11.mkdirSync(dir, { recursive: true }); + const file = wakeLockPath(teamDir); + try { + const fd = fs11.openSync(file, "wx", 384); + fs11.writeFileSync(fd, JSON.stringify({ pid: process.pid, at: now2 })); + fs11.closeSync(fd); + return true; + } catch { + try { + const stat = fs11.statSync(file); + if (now2 - stat.mtimeMs > WAKE_LOCK_STALE_MS) { + fs11.unlinkSync(file); + const fd = fs11.openSync(file, "wx", 384); + fs11.writeFileSync(fd, JSON.stringify({ pid: process.pid, at: now2 })); + fs11.closeSync(fd); + return true; + } + } catch { + } + return false; + } +} +function releaseLock(teamDir) { + try { + fs11.unlinkSync(wakeLockPath(teamDir)); + } catch { + } +} +async function maybeWakeLead(args) { + if (process.env.TEAM_WAKE_LEAD !== "1") return Promise.resolve({ woke: false, reason: "disabled" }); + const now2 = args.now ?? Date.now(); + const state = readLeadState(args.teamDir); + if (state === void 0) return Promise.resolve({ woke: false, reason: "no-lead-state" }); + if (state.active) return Promise.resolve({ woke: false, reason: "lead-active" }); + const updated = Date.parse(state.updatedAt); + if (Number.isNaN(updated) || now2 - updated < args.minIdleMs) { + return Promise.resolve({ woke: false, reason: "recent-activity" }); + } + if (state.lastWakeAt !== void 0) { + const last = Date.parse(state.lastWakeAt); + if (!Number.isNaN(last) && now2 - last < WAKE_COOLDOWN_MS) { + return Promise.resolve({ woke: false, reason: "cooldown" }); + } + } + if (!acquireLock(args.teamDir, now2)) return Promise.resolve({ woke: false, reason: "wake-locked" }); + const runDir = path10.join(leadDir(args.teamDir), "run"); + fs11.mkdirSync(runDir, { recursive: true }); + const stdoutFile = path10.join(runDir, `wake-${now2}.out`); + try { + const argv = [ + ...args.zcode.argvPrefix, + "-p", + WAKE_PROMPT, + "--json", + "--mode", + "yolo", + "--surface", + "terminal", + "--cwd", + args.cwd, + "--resume", + args.leadSessionId + ]; + if (args.launch !== void 0) { + await args.launch({ command: args.zcode.command, argv, cwd: args.cwd, stdoutFile }); + } else { + await spawnDetached({ + command: args.zcode.command, + argv, + env: process.env, + cwd: args.cwd, + stdoutFile + }); + } + writeLeadState(args.teamDir, { + ...state, + // 竞态保护:await launch 期间被拉起的 resume 回合可能已写锚/回合状态 → 重读合并, + // 不让这次 lastWakeAt 旧快照覆盖(soloNotifiedAt 丢失 = 下回合重复注入)。 + ...readLeadState(args.teamDir) ?? {}, + lastWakeAt: new Date(now2).toISOString() + }); + return { woke: true, reason: "launched" }; + } catch (err) { + return { woke: false, reason: `spawn-failed: ${err instanceof Error ? err.message : String(err)}` }; + } finally { + releaseLock(args.teamDir); + } +} +function leadWakeEnabled() { + return process.env.TEAM_WAKE_LEAD === "1"; +} + +// src/provider/transcript.ts +import fs12 from "node:fs"; +import os3 from "node:os"; +import path11 from "node:path"; +import { DatabaseSync } from "node:sqlite"; +function defaultDbPath() { + return process.env.TEAM_DB_PATH ?? path11.join(os3.homedir(), ".zcode", "cli", "db", "db.sqlite"); +} +var TranscriptReader = class { + dbPath; + db = null; + dbMissing = false; + constructor(deps = {}) { + this.dbPath = deps.dbPath ?? defaultDbPath(); + } + get path() { + return this.dbPath; + } + /** 库不存在 = 空库语义(探针方法走缺省值,不建临时库)。 */ + missing() { + if (!this.dbMissing) this.dbMissing = !fs12.existsSync(this.dbPath); + else if (!fs12.existsSync(this.dbPath)) return true; + else this.dbMissing = false; + return this.dbMissing; + } + open() { + if (this.db !== null) return this.db; + if (!fs12.existsSync(this.dbPath)) { + throw new Error("transcript db missing"); + } + this.db = new DatabaseSync(this.dbPath, { readOnly: true }); + return this.db; + } + close() { + this.db?.close(); + this.db = null; + } + /** 会话行实查;不存在 → undefined;读失败 → 抛错。 */ + session(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + "SELECT id, parent_id, directory, task_type, title, time_created FROM session WHERE id = ?" + ).get(sessionId); + return row ?? void 0; + } + /** 找「目录 = cwd 且创建于 sinceMs 之后、首条真实用户文本 = firstPrompt」的会话(fresh spawn 探针)。 */ + findSessionByFirstPrompt(args) { + if (this.missing()) return void 0; + const rows = this.open().prepare( + "SELECT id, time_created FROM session WHERE directory = ? AND time_created >= ? ORDER BY time_created ASC" + ).all(args.cwd, args.sinceMs - 2e3); + for (const row of rows) { + if (args.excludeSessionIds?.has(row.id)) continue; + const first = this.firstRealUserText(row.id); + if (first === args.firstPrompt) return row.id; + } + return void 0; + } + /** 首条「真实用户」消息的文本部分(跳过 hook/系统注入的 model-only 消息)。 */ + firstRealUserText(sessionId) { + if (this.missing()) return null; + const rows = this.open().prepare( + `SELECT p.data pdata FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + ORDER BY m.sequence, p.sequence LIMIT 1` + ).all(sessionId); + if (rows.length === 0) return null; + return extractText(rows[0].pdata); + } + /** 会话中是否已存在该文本的「真实用户」消息(delivered/去重探针:prompt 逐字落库)。 */ + hasUserText(sessionId, text) { + if (this.missing()) return false; + const row = this.open().prepare( + `SELECT COUNT(*) n FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + AND json_extract(p.data,'$.text') = ? LIMIT 1` + ).get(sessionId, text); + return row.n > 0; + } + /** 会话全部「真实用户」文本消息(时间序;轮次 prompt 审计/恰一次检索用)。 */ + realUserTexts(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.id mid, m.time_created tc, p.data pdata, + json_extract(m.data,'$.semantics.origin') origin, + json_extract(m.data,'$.modelSelection.modelId') model + FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + return rows.map((r) => ({ + messageId: r.mid, + text: extractText(r.pdata) ?? "", + timeCreated: r.tc, + origin: r.origin, + modelId: r.model + })); + } + /** 会话最新使用的模型(成员行 model 字段实查;无消息 → undefined)。 */ + latestModel(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT json_extract(m.data,'$.modelSelection.modelId') model FROM message m + WHERE m.session_id = ? AND json_extract(m.data,'$.modelSelection.modelId') IS NOT NULL + ORDER BY m.sequence DESC LIMIT 1` + ).get(sessionId); + return row?.model; + } + /** + * 最近一条「真实用户提交」(semantics.origin=real_user)消息携带的模型快照 + 提交时间。 + * 0.4.0 三源判定的「提交证据」:宿主保存用户消息时写入该次提交的 modelSelection(本机源码核对), + * 输入框切换在提交瞬间即体现在这里——不依赖会话选模条目(issue #7 场景它可能滞后)。 + * hook/系统注入的 user 消息(origin≠real_user)不算提交。 + */ + latestSubmissionSelection(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT m.time_created tc, + json_extract(m.data,'$.modelSelection.providerId') p, + json_extract(m.data,'$.modelSelection.modelId') mo, + json_extract(m.data,'$.modelSelection.options.reasoningLevel') lvl + FROM message m + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(m.data,'$.modelSelection.providerId') IS NOT NULL + AND json_extract(m.data,'$.modelSelection.modelId') IS NOT NULL + ORDER BY m.time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.p.trim(); + const modelId = row.mo.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const lvl = typeof row.lvl === "string" ? row.lvl.trim() : ""; + return { + selection: { providerId, modelId, ...lvl.length > 0 ? { reasoningLevel: lvl } : {} }, + at: row.tc + }; + } + /** 会话选模条目 + 生效时间(UPSERT 单行;用于与提交快照比较「后来是否有 /model 修改」)。 */ + latestModelSelectionTimed(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT data, MAX(COALESCE(time_updated, time_created), time_created) at FROM session_entry + WHERE session_id = ? AND type = 'runtime/model_selection' + ORDER BY time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const selection = this.latestModelSelection(sessionId); + if (selection === void 0) return void 0; + return { selection, at: row.at }; + } + /** + * 最近一次**主轮**实际模型调用(+ 开始时间)。query_source='main_turn' 过滤是 0.4.0 关键口径: + * compact/标题生成/goal 摘要/subagent/workflow 子轮的行属于辅助模型,绝不能当作 Lead 当前模型 + * (实测本机取值域 = compact, goal_summary_title, main_turn, session_title, subagent, + * target_completion_verification, workflow_child)。 + */ + latestMainTurnUsage(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT provider_id, model_id, variant, started_at FROM model_usage + WHERE session_id = ? AND query_source = 'main_turn' + ORDER BY started_at DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.provider_id.trim(); + const modelId = row.model_id.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const variant = typeof row.variant === "string" ? row.variant.trim() : ""; + return { + selection: { providerId, modelId, ...variant.length > 0 ? { reasoningLevel: variant } : {} }, + at: row.started_at + }; + } + /** + * 会话库中最近一次 setModel 的选择(Round A 实证:条目为 UPSERT 单行,canonical id + * `:runtime-model-selection`,时间排序安全)。data 取嵌套 modelSelection 优先; + * 兼容旧行把 providerId/modelId/thoughtLevel 平铺在顶层的形态。 + */ + latestModelSelection(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT data FROM session_entry + WHERE session_id = ? AND type = 'runtime/model_selection' + ORDER BY time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const data = parseOrNull(row.data); + if (data === null) return void 0; + const nested = parseModelSelection(data.modelSelection); + if (nested !== void 0) return nested; + const providerId = typeof data.providerId === "string" ? data.providerId.trim() : ""; + const modelId = typeof data.modelId === "string" ? data.modelId.trim() : ""; + if (providerId.length === 0 || modelId.length === 0) return void 0; + const thoughtLevel = typeof data.thoughtLevel === "string" ? data.thoughtLevel.trim() : ""; + return { + providerId, + modelId, + ...thoughtLevel.length > 0 ? { reasoningLevel: thoughtLevel } : {} + }; + } + /** 最近一次真实模型调用(session_entry 缺失时的继承兜底;variant = 思考强度)。 */ + latestModelUsage(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT provider_id, model_id, variant FROM model_usage + WHERE session_id = ? ORDER BY started_at DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.provider_id.trim(); + const modelId = row.model_id.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const variant = typeof row.variant === "string" ? row.variant.trim() : ""; + return { + providerId, + modelId, + ...variant.length > 0 ? { reasoningLevel: variant } : {} + }; + } + /** 完成回合导出(D3 fork 转录):真实用户消息 + 助手文本;tool 部分记工具名。 */ + exportTurns(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.data mdata, p.data pdata FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + const turns = []; + for (const r of rows) { + const message = parseOrNull(r.mdata); + const part = parseOrNull(r.pdata); + if (message === null || part === null) continue; + const isUser = message.role === "user"; + const isAssistant = message.role === "assistant"; + const realUser = isUser && message.semantics?.origin === "real_user"; + if (part.type === "text" && typeof part.text === "string") { + if (realUser) turns.push({ role: "user", text: part.text, toolNames: [] }); + else if (isAssistant) turns.push({ role: "assistant", text: part.text, toolNames: [] }); + } else if (isAssistant && part.type === "tool" && typeof part.tool === "string") { + const last = turns[turns.length - 1]; + if (last !== void 0 && last.role === "assistant" && !last.toolNames.length) { + last.toolNames.push(part.tool); + } else { + turns.push({ role: "assistant", text: "", toolNames: [part.tool] }); + } + } + } + return turns; + } + /** + * T5.7 成员会话查看视图导出(detail 合成数据源;只读、走 session_id 索引): + * 时间序全量 part 行(text/tool 两型;其余 part 型跳过),损坏行跳过。 + * 与 exportTurns 的区别:保留每条 part 的时间戳/role/工具状态(面板折叠行渲染), + * 不做回合聚合;hook 注入文本不落 transcript part(H14),framed 徽标由 + * panel/detail.ts 以 events 回填(不改写原文)。 + */ + exportDetailParts(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.data mdata, m.time_created mtc, p.data pdata, p.time_created ptc + FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + const out = []; + for (const r of rows) { + const message = parseOrNull(r.mdata); + const part = parseOrNull(r.pdata); + if (message === null || part === null) continue; + const role = message.role === "user" ? "user" : message.role === "assistant" ? "assistant" : void 0; + if (role === void 0) continue; + if (role === "user" && message.semantics?.origin !== "real_user") continue; + const ts2 = typeof r.ptc === "number" ? r.ptc : r.mtc; + if (part.type === "text" && typeof part.text === "string") { + out.push({ ts: ts2, role, kind: "text", text: part.text }); + } else if (part.type === "tool" && typeof part.tool === "string") { + const status = typeof part.state?.status === "string" ? part.state.status : "unknown"; + out.push({ + ts: ts2, + role: "assistant", + kind: "toolCall", + toolName: part.tool, + toolStatus: status, + ...part.state?.input !== void 0 ? { toolInput: part.state.input } : {}, + ...part.state?.output !== void 0 ? { toolOutput: part.state.output } : {} + }); + } + } + return out; + } +}; +function parseOrNull(raw) { + try { + return JSON.parse(raw); + } catch { + return null; + } +} +function extractText(partData) { + try { + const part = JSON.parse(partData); + return typeof part.text === "string" ? part.text : null; + } catch { + return null; + } +} + +// src/provider/fork-context.ts +var FORK_HEADER = "[Agent Teams fork context] Your Team Lead's session transcript so far (for context inheritance):"; +var FORK_FOOTER = "[End of fork context]"; +function buildForkFirstPrompt(reader, leadSessionId, task, opts = {}) { + const maxChars = opts.maxChars ?? Number(process.env.TEAM_FORK_MAX_CHARS ?? 24e3); + const turns = reader.exportTurns(leadSessionId); + const kept = truncateTurns(turns, maxChars); + const lines = [FORK_HEADER]; + kept.turns.forEach((turn, i) => { + lines.push(`--- ${turn.role} #${i + 1} ---`); + if (turn.text.length > 0) lines.push(turn.text); + if (turn.toolNames.length > 0) lines.push(`[tools used: ${turn.toolNames.join(", ")}]`); + }); + lines.push(FORK_FOOTER); + lines.push(""); + lines.push(task); + return { + prompt: lines.join("\n"), + includedTurns: kept.turns.length, + truncated: kept.truncated + }; +} +function truncateTurns(turns, maxChars) { + if (turns.length === 0) return { turns: [], truncated: false }; + const rendered = (t) => t.text.length > 0 ? t.text : `[tools used: ${t.toolNames.join(", ")}]`; + const totalChars = turns.reduce((sum, t) => sum + rendered(t).length, 0); + if (totalChars <= maxChars) return { turns: [...turns], truncated: false }; + const first = turns[0]; + const budget = maxChars - rendered(first).length; + const tail = []; + let used = 0; + for (let i = turns.length - 1; i >= 1; i--) { + const cost = rendered(turns[i]).length; + if (used + cost > budget && tail.length > 0) break; + tail.unshift(turns[i]); + used += cost; + } + return { turns: [first, ...tail], truncated: true }; +} + +// src/provider/zcode-bin.ts +import fs13 from "node:fs"; +import path12 from "node:path"; +import { execFileSync } from "node:child_process"; +var DESKTOP_ZCODE_CJS = "/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs"; +function resolveZcodeBin(env = process.env) { + const explicit = env.TEAM_ZCODE_BIN; + if (explicit && explicit.trim()) { + return binFor(explicit.trim(), "env"); + } + const rg = env.ZCODE_RG_BINARY; + if (rg && rg.trim()) { + const derived = path12.join(path12.dirname(path12.dirname(path12.dirname(rg))), "glm", "zcode.cjs"); + if (fs13.existsSync(derived)) return binFor(derived, "rg-derive"); + } + if (fs13.existsSync(DESKTOP_ZCODE_CJS)) return binFor(DESKTOP_ZCODE_CJS, "desktop-default"); + try { + const which = execFileSync("which", ["zcode"], { encoding: "utf8" }).trim(); + if (which.length > 0) return binFor(which, "which"); + } catch { + } + throw new Error( + "cannot locate the zcode CLI binary: set TEAM_ZCODE_BIN (daemon env) or install ZCode Desktop" + ); +} +function binFor(p, source) { + if (/\.(cjs|mjs|js)$/.test(p)) { + return { command: process.execPath, argvPrefix: [p], source }; + } + return { command: p, argvPrefix: [], source }; +} + +// src/provider/session-breeder.ts +import fs16 from "node:fs"; +import os6 from "node:os"; +import path15 from "node:path"; +import { DatabaseSync as DatabaseSync3 } from "node:sqlite"; + +// src/provider/app-server-client.mjs +import { execFile as execFile2 } from "node:child_process"; +import fs14 from "node:fs"; +import os4 from "node:os"; +import path13 from "node:path"; +import { fileURLToPath as fileURLToPath2 } from "node:url"; +var BRIDGE_DEFAULT = path13.join(path13.dirname(fileURLToPath2(import.meta.url)), "app-server-bridge.mjs"); +var AppServerClient = class _AppServerClient { + #child; + #specFile; + #buffer = ""; + #nextId = 1; + #pending = /* @__PURE__ */ new Map(); + #notifications = []; + #stderr = ""; + #closed = false; + #exited = false; + #log; + constructor(opts) { + this.#log = opts.log; + const specDir = fs14.mkdtempSync(path13.join(os4.tmpdir(), "at-appserver-")); + try { + fs14.chmodSync(specDir, 448); + } catch { + } + this.#specFile = path13.join(specDir, "spec.json"); + fs14.writeFileSync( + this.#specFile, + JSON.stringify({ + executable: opts.executable, + argv: [...opts.argvPrefix, "app-server"], + cwd: opts.cwd + }), + { mode: 384 } + ); + const bridge = process.env.TEAM_APP_SERVER_BRIDGE ?? BRIDGE_DEFAULT; + this.#child = execFile2( + process.execPath, + ["--", bridge, this.#specFile], + { cwd: opts.cwd, timeout: 0, maxBuffer: 8 * 1024 * 1024, env: opts.env ?? process.env }, + (err) => { + this.#exited = true; + const error2 = err ?? new Error("app-server exited"); + for (const [, pending] of this.#pending) { + clearTimeout(pending.timer); + pending.reject(error2); + } + this.#pending.clear(); + } + ); + this.#child.stdout?.on("data", (chunk) => this.#onStdout(String(chunk))); + this.#child.stderr?.on("data", (chunk) => { + this.#stderr += String(chunk); + if (this.#stderr.length > 32e3) this.#stderr = this.#stderr.slice(-32e3); + }); + this.#child.on("exit", () => { + this.#exited = true; + }); + } + /** 校验可执行文件为绝对路径后启动(相对路径/空串一律拒绝)。 */ + static spawn(opts) { + if (typeof opts.executable !== "string" || !path13.isAbsolute(opts.executable)) { + throw new Error("app-server executable must be an absolute path"); + } + return new _AppServerClient(opts); + } + #onStdout(text) { + this.#buffer += text; + let index; + while ((index = this.#buffer.indexOf("\n")) >= 0) { + const line = this.#buffer.slice(0, index).trim(); + this.#buffer = this.#buffer.slice(index + 1); + if (line.length === 0) continue; + let message; + try { + message = JSON.parse(line); + } catch { + continue; + } + if (typeof message.id === "number" && this.#pending.has(message.id)) { + const pending = this.#pending.get(message.id); + this.#pending.delete(message.id); + clearTimeout(pending.timer); + if (message.error !== void 0) { + const error2 = new Error(message.error.message ?? "app-server rpc error"); + error2.rpc = message.error; + pending.reject(error2); + } else { + pending.resolve(message.result); + } + continue; + } + if (typeof message.method === "string") { + this.#notifications.push({ method: message.method, params: message.params }); + if (message.id !== void 0 && message.id !== null) { + const result = message.method === "session/requestRuntimePreferences" ? { + nativeSearchEnhancementsEnabled: true, + memoryEnabled: false, + askUserQuestionAutoResolutionEnabled: true + } : null; + this.#write({ id: message.id, result }); + } + } + } + } + #write(message) { + if (this.#closed || this.#child.stdin === null || this.#child.stdin.destroyed) return; + this.#child.stdin.write(`${JSON.stringify(message)} +`); + } + /** 等待 startup/storageState ready(超时返回 false,不抛错)。 */ + async waitReady(timeoutMs = 2e4) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (this.#notifications.some( + (n) => n.method === "startup/storageState" && n.params?.phase === "ready" + )) { + return true; + } + if (this.#exited) return false; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + return false; + } + rpc(method, params, timeoutMs = 3e4, opts = {}) { + if (this.#closed) return Promise.reject(new Error("app-server client is closed")); + if (opts.signal?.aborted) return Promise.reject(opts.signal.reason ?? new Error("aborted")); + const id = this.#nextId++; + return new Promise((resolve, reject) => { + const onAbort = () => { + this.#pending.delete(id); + clearTimeout(timer); + reject(opts.signal.reason ?? new Error("aborted")); + }; + opts.signal?.addEventListener("abort", onAbort, { once: true }); + const timer = setTimeout(() => { + this.#pending.delete(id); + opts.signal?.removeEventListener("abort", onAbort); + const error2 = new Error(`app-server rpc timeout: ${method}`); + error2.outcome = "unknown"; + reject(error2); + }, timeoutMs); + timer.unref?.(); + this.#pending.set(id, { + resolve: (result) => { + opts.signal?.removeEventListener("abort", onAbort); + resolve(result); + }, + reject: (error2) => { + opts.signal?.removeEventListener("abort", onAbort); + reject(error2); + }, + timer + }); + this.#write({ id, method, params }); + }); + } + getStderr() { + return this.#stderr; + } + async close() { + if (this.#closed) return; + this.#closed = true; + for (const [, pending] of this.#pending) { + clearTimeout(pending.timer); + pending.reject(new Error("app-server client closed")); + } + this.#pending.clear(); + try { + this.#child.stdin?.end(); + } catch { + } + if (!this.#exited) { + try { + this.#child.kill("SIGTERM"); + } catch { + } + await new Promise((resolve) => { + const timer = setTimeout(() => { + try { + this.#child.kill("SIGKILL"); + } catch { + } + resolve(); + }, 1500); + timer.unref?.(); + this.#child.once("exit", () => { + clearTimeout(timer); + resolve(); + }); + }); + } + try { + fs14.rmSync(path13.dirname(this.#specFile), { recursive: true, force: true }); + } catch { + } + this.#log?.({ event: "app-server-closed", stderrTail: this.#stderr.slice(-800) }); + } +}; + +// src/sidebar/tasks-index.ts +import fs15 from "node:fs"; +import os5 from "node:os"; +import path14 from "node:path"; +import { DatabaseSync as DatabaseSync2 } from "node:sqlite"; +var ANCHOR_TITLE = "Agent Team anchor"; +function defaultTasksIndexPath() { + return process.env.TEAM_TASKS_INDEX ?? path14.join(os5.homedir(), ".zcode", "v2", "tasks-index.sqlite"); +} +function withRetry(fn, attempts = 3) { + let last; + for (let i = 0; i < attempts; i += 1) { + try { + return fn(); + } catch (err) { + last = err; + const message = err instanceof Error ? err.message : String(err); + if (!/SQLITE_BUSY|database is locked/i.test(message)) throw err; + const until = Date.now() + 100 * (i + 1); + while (Date.now() < until) { + } + } + } + throw last; +} +function tombstoneAnchor(input) { + const dbPath = input.dbPath ?? defaultTasksIndexPath(); + if (!fs15.existsSync(dbPath)) return { applied: false, reason: "tasks-index-missing" }; + const now2 = input.now ?? Date.now(); + return withRetry(() => { + const db = new DatabaseSync2(dbPath); + try { + db.exec("PRAGMA busy_timeout = 5000"); + db.exec("BEGIN IMMEDIATE"); + const existing = db.prepare("select task_id, title, workspace_path from tasks where task_id = ?").get(input.taskId); + if (existing !== void 0 && existing.workspace_path === input.workspacePath && existing.title !== "" && existing.title !== "Untitled session" && existing.title !== ANCHOR_TITLE) { + db.exec("ROLLBACK"); + return { applied: false, reason: "row-not-owned" }; + } + if (existing !== void 0 && existing.workspace_path !== input.workspacePath) { + db.exec("ROLLBACK"); + return { applied: false, reason: "row-not-owned" }; + } + const meta = JSON.stringify({ + taskId: input.taskId, + title: ANCHOR_TITLE, + workspacePath: input.workspacePath, + createdAt: now2, + updatedAt: now2, + mode: "default", + provider: "glm", + status: "completed", + titleOverridden: false + }); + db.prepare( + `INSERT INTO tasks ( + workspace_key, workspace_path, workspace_identity, task_id, title, task_status, + provider, mode, model, migration_source, forked_from_task_id, cron_automation_id, + off_peak_task_id, created_at, updated_at, unread_at, last_unread_at, pinned, + archived, deleted, title_overridden, searchable_text, meta_json + ) VALUES ( + @workspace_key, @workspace_path, NULL, @task_id, @title, 'completed', + 'glm', 'default', NULL, NULL, NULL, NULL, + NULL, @now, @now, NULL, 0, 0, + 0, 1, 0, @searchable, @meta + ) + ON CONFLICT(workspace_key, task_id) DO UPDATE SET + deleted = 1, + updated_at = excluded.updated_at + WHERE tasks.task_id = excluded.task_id + AND (tasks.title = '' OR tasks.title = 'Untitled session' OR tasks.title = @title)` + ).run({ + workspace_key: input.workspacePath, + workspace_path: input.workspacePath, + task_id: input.taskId, + title: ANCHOR_TITLE, + now: now2, + searchable: ANCHOR_TITLE, + meta + }); + db.exec("COMMIT"); + return { applied: true }; + } catch (err) { + try { + db.exec("ROLLBACK"); + } catch { + } + throw err; + } finally { + db.close(); + } + }); +} + +// src/provider/session-breeder.ts +function defaultSessionDbPath() { + return process.env.TEAM_DB_PATH ?? path15.join(os6.homedir(), ".zcode", "cli", "db", "db.sqlite"); +} +var BreedError = class extends Error { + constructor(code, message) { + super(message); + this.code = code; + this.name = "BreedError"; + } +}; +var AppServerSessionBreeder = class { + zcode; + tasksIndexPath; + dbPath; + log; + now; + readyTimeoutMs; + constructor(opts = {}) { + this.zcode = opts.zcode ?? resolveZcodeBin(); + this.tasksIndexPath = opts.tasksIndexPath ?? defaultTasksIndexPath(); + this.dbPath = opts.dbPath ?? defaultSessionDbPath(); + this.log = opts.log ?? (() => void 0); + this.now = opts.now ?? Date.now; + this.readyTimeoutMs = opts.readyTimeoutMs ?? 2e4; + } + /** + * 解析 Leader 会话的真实工作目录(只读)。 + * daemon 由宿主跨工作区复用,`TEAM_PROJECT_DIR` 可能来自首个启动工作区—— + * anchor 必须建在 Lead 自己的目录,否则 teammate 工具 cwd 会错。 + */ + resolveWorkspace(leadSessionId, fallback) { + if (!fs16.existsSync(this.dbPath)) return path15.resolve(fallback); + try { + const db = new DatabaseSync3(this.dbPath, { readOnly: true }); + try { + const row = db.prepare("select directory from session where id = ?").get(leadSessionId); + if (typeof row?.directory === "string" && row.directory.length > 0) { + return path15.resolve(row.directory); + } + } finally { + db.close(); + } + } catch { + } + return path15.resolve(fallback); + } + /** + * 培育失败清理:把已创建的 anchor 再写一次 tombstone(幂等),防止 child 未建成时 + * anchor 暴露到左侧任务栏。仅 anchor 行(D25 白名单),不触碰其他行。 + */ + disposeBredSessions(input) { + try { + const result = tombstoneAnchor({ + taskId: input.anchorSessionId, + workspacePath: input.workspacePath, + dbPath: this.tasksIndexPath, + now: this.now() + }); + this.log({ + event: "session-breed-dispose", + anchorSessionId: input.anchorSessionId, + applied: result.applied, + reason: result.reason ?? null + }); + return result; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + this.log({ event: "session-breed-dispose-failed", anchorSessionId: input.anchorSessionId, message }); + return { applied: false, reason: message }; + } + } + /** 造一个隐藏子会话;失败抛 BreedError(不回退成可见会话——DSH 口径:失败即 failed 成员)。 */ + async createChild(input) { + const startedAt = this.now(); + const workspacePath = this.resolveWorkspace(input.teamId, input.workspacePath); + const client = this.#spawnClient(workspacePath); + const anchorCommandId = input.anchorCommandId ?? `team-anchor-${startedAt}-${Math.random().toString(36).slice(2, 8)}`; + const childCommandId = input.childCommandId ?? `team-child-${this.now()}-${Math.random().toString(36).slice(2, 8)}`; + const commandTimeoutMs = input.timeoutMs ?? 3e4; + const queryTimeoutMs = Math.min(input.timeoutMs ?? 5e3, 5e3); + let anchorSessionId = input.anchorSessionId ?? null; + let childSessionId = null; + let anchorEvidence = false; + try { + const readyTimeoutMs = this.readyTimeoutMs; + const ready = await client.waitReady(readyTimeoutMs); + if (!ready) { + throw new BreedError( + "startup-timeout", + `app-server did not become ready within ${readyTimeoutMs}ms` + ); + } + if (input.signal?.aborted) { + throw new BreedError("outcome-unknown", abortDescription(input.signal, "session breeding aborted")); + } + let priorChild; + const hasRecoveryIdentity = input.anchorCommandId !== void 0 && input.childCommandId !== void 0 && input.anchorSessionId !== void 0 && input.recoveryEvidence === true; + if (hasRecoveryIdentity) { + const priorAnchor = await this.#queryCommand(client, { + commandId: anchorCommandId, + sessionId: null, + type: "createSession", + signal: input.signal, + timeoutMs: queryTimeoutMs + }); + if (priorAnchor !== "unknown") { + anchorSessionId = createdSessionId(priorAnchor, { + type: "createSession", + expectedSessionId: input.anchorSessionId, + failure: "create-rejected", + mismatchFailure: "outcome-unknown" + }); + anchorEvidence = true; + } else { + anchorSessionId = await this.#findPreallocatedAnchor(client, { + anchorSessionId: input.anchorSessionId, + workspacePath, + signal: input.signal, + timeoutMs: queryTimeoutMs + }); + anchorEvidence = anchorSessionId !== null; + } + if (anchorEvidence && anchorSessionId !== null) { + this.reportProgress(input, { anchorSessionId, stage: "anchor-recovered" }); + priorChild = await this.#queryCommand(client, { + commandId: childCommandId, + sessionId: anchorSessionId, + type: "createSelectionSideSession", + signal: input.signal, + timeoutMs: queryTimeoutMs + }); + } + } + if (!anchorEvidence) { + const anchorCall = await this.#runCommand(client, { + commandId: anchorCommandId, + sessionId: null, + issuedAt: startedAt, + type: "createSession", + payload: { + ...input.anchorSessionId !== void 0 ? { sessionId: input.anchorSessionId } : {}, + workspaceId: workspacePath, + permissionScope: "session" + }, + signal: input.signal, + commandTimeoutMs, + queryTimeoutMs + }); + const createdAnchorId = createdSessionId(anchorCall.ack, { + type: "createSession", + expectedSessionId: input.anchorSessionId, + failure: "create-rejected", + mismatchFailure: anchorCall.recovered ? "outcome-unknown" : "create-rejected" + }); + anchorSessionId = createdAnchorId; + anchorEvidence = true; + this.reportProgress(input, { anchorSessionId: createdAnchorId, stage: "anchor-created" }); + } + if (anchorSessionId === null) { + throw new BreedError("outcome-unknown", "anchor has no confirmed session id; not creating a replacement"); + } + const tombstone = tombstoneAnchor({ + taskId: anchorSessionId, + workspacePath, + dbPath: this.tasksIndexPath, + now: this.now() + }); + if (!tombstone.applied && tombstone.reason === "row-not-owned") { + throw new BreedError( + "create-rejected", + `anchor "${anchorSessionId}" task row is not owned by agent-team; refusing to continue` + ); + } + const commandArgs = { + commandId: childCommandId, + sessionId: anchorSessionId, + issuedAt: this.now(), + type: "createSelectionSideSession", + payload: {}, + signal: input.signal, + commandTimeoutMs, + queryTimeoutMs + }; + let sideCall; + let recoveredChildNeedsResume = false; + if (priorChild !== void 0 && priorChild !== "unknown") { + recoveredChildNeedsResume = input.modelSelection !== void 0; + sideCall = { ack: priorChild, recovered: true }; + } else { + sideCall = await this.#runCommand(client, commandArgs); + } + const createdChildId = createdSessionId(sideCall.ack, { + type: "createSelectionSideSession", + failure: "command-rejected", + mismatchFailure: sideCall.recovered ? "outcome-unknown" : "command-rejected" + }); + childSessionId = createdChildId; + this.reportProgress(input, { + anchorSessionId, + childSessionId: createdChildId, + stage: "child-created" + }); + if (recoveredChildNeedsResume) { + await client.rpc( + "session/resume", + { sessionId: createdChildId }, + queryTimeoutMs, + { signal: input.signal } + ); + } + let appliedModel; + if (input.modelSelection !== void 0) { + try { + await this.#setModel(client, childSessionId, input.modelSelection, input.signal); + appliedModel = input.modelSelection; + this.log({ + event: "model-set", + teamId: input.teamId, + childSessionId, + providerId: input.modelSelection.providerId, + modelId: input.modelSelection.modelId, + reasoningLevel: input.modelSelection.reasoningLevel ?? null + }); + this.reportProgress(input, { + anchorSessionId, + childSessionId, + stage: "model-applied" + }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + this.log({ + event: "model-set-failed", + teamId: input.teamId, + childSessionId, + providerId: input.modelSelection.providerId, + modelId: input.modelSelection.modelId, + message + }); + if (input.signal?.aborted) { + throw new BreedError("outcome-unknown", abortDescription(input.signal, message)); + } + throw new BreedError( + "model-rejected", + `member could not use the inherited model ${input.modelSelection.providerId}/${input.modelSelection.modelId}: ${message}` + ); + } + } + if (anchorSessionId === null || childSessionId === null) { + throw new BreedError("unsupported", "session breeding produced no anchor/child id"); + } + const elapsedMs = this.now() - startedAt; + this.log({ + event: "session-bred", + teamId: input.teamId, + anchorSessionId, + childSessionId, + tombstone, + elapsedMs + }); + return { + anchorSessionId, + childSessionId, + elapsedMs, + workspacePath, + ...appliedModel !== void 0 ? { appliedModel } : {} + }; + } catch (err) { + const stderr = client.getStderr().slice(-800); + const mayDispose = anchorEvidence && !(err instanceof BreedError && err.code === "outcome-unknown") && !input.signal?.aborted; + if (err instanceof BreedError) { + this.log({ + event: "session-breed-failed", + teamId: input.teamId, + code: err.code, + message: err.message, + stderr, + anchorSessionId, + childSessionId + }); + if (mayDispose && anchorSessionId !== null) { + this.disposeBredSessions({ anchorSessionId, workspacePath }); + } + throw err; + } + const message = err instanceof Error ? err.message : String(err); + const code = input.signal?.aborted ? "outcome-unknown" : /timeout/i.test(message) ? "startup-timeout" : /exited|ENOENT|EACCES|spawn/i.test(message) ? "spawn-failed" : "unsupported"; + this.log({ + event: "session-breed-failed", + teamId: input.teamId, + code, + message, + stderr, + anchorSessionId, + childSessionId + }); + if (mayDispose && anchorSessionId !== null) { + this.disposeBredSessions({ anchorSessionId, workspacePath }); + } + throw new BreedError(code, `${message}${stderr.length > 0 ? ` | stderr: ${stderr}` : ""}`); + } finally { + await client.close(); + } + } + /** 每轮执行前同步(0.4.0):同 createChild 会话活跃前提下 setModel;失败返回原因(调用方阻止本轮)。 */ + async applyModelSelection(input) { + const readyTimeoutMs = input.timeoutMs ?? this.readyTimeoutMs; + let client; + try { + client = this.#spawnClient(input.workspacePath); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + this.log({ event: "model-apply-failed", sessionId: input.sessionId, reason }); + return { applied: false, reason }; + } + try { + const ready = await client.waitReady(readyTimeoutMs); + if (!ready) { + const reason = `app-server did not become ready within ${readyTimeoutMs}ms`; + this.log({ event: "model-apply-failed", sessionId: input.sessionId, reason }); + return { applied: false, reason }; + } + await client.rpc("session/resume", { sessionId: input.sessionId }, 2e4); + await this.#setModel(client, input.sessionId, input.selection); + this.log({ + event: "model-applied", + sessionId: input.sessionId, + providerId: input.selection.providerId, + modelId: input.selection.modelId, + reasoningLevel: input.selection.reasoningLevel ?? null + }); + return { applied: true }; + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + this.log({ event: "model-apply-failed", sessionId: input.sessionId, reason }); + return { applied: false, reason }; + } finally { + await client.close(); + } + } + /** + * 应用一次模型选择(createChild 首轮 / launchTurn 每轮同步共用)。 + * result 是巨型消息快照(PoC 事实 1):只记目标三元组与错误文本,绝不整包落日志。 + */ + /** setModel 请求体(createChild / applyModelSelection 共用;persistAsWorkspaceLastUsed 恒 false)。 */ + async #setModel(client, sessionId, selection, signal) { + await client.rpc( + "session/setModel", + { + sessionId, + model: { + providerId: selection.providerId, + modelId: selection.modelId, + ...selection.reasoningLevel !== void 0 ? { options: { reasoningLevel: selection.reasoningLevel } } : {} + }, + persistAsWorkspaceLastUsed: false + }, + 2e4, + { signal } + ); + } + reportProgress(input, progress) { + if (input.onProgress?.(progress) === false) { + throw new BreedError("outcome-unknown", "coordinator generation revoked; host evidence is retained for recovery"); + } + } + async #runCommand(client, input) { + try { + const ack = await client.rpc("v4/command", commandEnvelope(input), input.commandTimeoutMs, { + signal: input.signal + }); + return { ack, recovered: false }; + } catch (err) { + if (input.signal?.aborted) { + throw new BreedError("outcome-unknown", abortDescription(input.signal, errorDescription(err))); + } + const message = errorDescription(err); + if (/invalid params|method not found|invalid request/i.test(message)) throw err; + const ack = await this.#queryCommand(client, { + commandId: input.commandId, + sessionId: input.sessionId, + type: input.type, + signal: input.signal, + timeoutMs: input.queryTimeoutMs + }); + if (ack === "unknown") { + throw new BreedError("outcome-unknown", `${input.type} outcome is unknown; original command was not replayed`); + } + return { ack, recovered: true }; + } + } + async #queryCommand(client, input) { + let queried; + try { + queried = await client.rpc( + "v4/commands/query", + { commands: [{ sessionId: input.sessionId, commandId: input.commandId }] }, + input.timeoutMs, + { signal: input.signal } + ); + } catch (err) { + const message = errorDescription(err); + throw new BreedError( + "outcome-unknown", + `${input.type} outcome is unknown; command query could not establish a final result: ${message}` + ); + } + const matches = (queried?.results ?? []).filter( + (entry) => entry?.key?.commandId === input.commandId && entry.key.sessionId === input.sessionId + ); + const result = matches.length === 1 ? matches[0].result : "unknown"; + if (result === "unknown") return "unknown"; + if (typeof result !== "object" || result === null) { + throw new BreedError( + "outcome-unknown", + `${input.type} outcome is unknown; malformed command result for "${input.commandId}"` + ); + } + if (result.status === "accepted" || result.status === "duplicate") { + return result; + } + if (isExplicitRejection(result)) { + throw new BreedError( + input.type === "createSession" ? "create-rejected" : "command-rejected", + describeAck(input.type, result) + ); + } + throw new BreedError( + "outcome-unknown", + `${input.type} outcome is unknown; command "${input.commandId}" has non-final status "${result.status ?? "missing"}"` + ); + } + /** 仅对预分配 anchor 使用:必须同时证明 id、workspace 和非子会话类型,绝不认领近似对象。 */ + async #findPreallocatedAnchor(client, input) { + let listed; + try { + listed = await client.rpc( + "session/list", + { sessionIds: [input.anchorSessionId] }, + input.timeoutMs, + { signal: input.signal } + ); + } catch (err) { + throw new BreedError( + "outcome-unknown", + `createSession outcome is unknown; anchor lookup failed: ${errorDescription(err)}` + ); + } + const matches = (listed?.sessions ?? []).filter((session2) => session2?.sessionId === input.anchorSessionId); + if (matches.length === 0) return null; + const session = matches[0]; + const sessionWorkspace = session.workspace?.workspacePath; + if (matches.length !== 1 || typeof sessionWorkspace !== "string" || path15.resolve(sessionWorkspace) !== path15.resolve(input.workspacePath) || session.sessionKind !== "interactive") { + throw new BreedError( + "outcome-unknown", + `createSession outcome is unknown; preallocated anchor "${input.anchorSessionId}" failed workspace/type verification` + ); + } + return input.anchorSessionId; + } + #spawnClient(workspacePath) { + try { + return AppServerClient.spawn({ + executable: this.zcode.command, + argvPrefix: this.zcode.argvPrefix, + cwd: workspacePath, + log: this.log + }); + } catch (err) { + throw new BreedError( + "spawn-failed", + `app-server spawn failed: ${err instanceof Error ? err.message : String(err)}` + ); + } + } +}; +function commandEnvelope(input) { + return { + commandId: input.commandId, + clientId: "agent-team", + sessionId: input.sessionId, + issuedAt: input.issuedAt, + type: input.type, + payload: input.payload + }; +} +function createdSessionId(ack, input) { + if (ack.status === "accepted" || ack.status === "duplicate") { + const id = ack.result?.sessionId; + if (ack.result?.type === input.type && typeof id === "string" && id.length > 0 && (input.expectedSessionId === void 0 || id === input.expectedSessionId)) { + return id; + } + throw new BreedError( + input.mismatchFailure, + `${input.type} returned mismatched result: ${describeAck(input.type, ack)}` + ); + } + if (isExplicitRejection(ack)) throw new BreedError(input.failure, describeAck(input.type, ack)); + throw new BreedError("outcome-unknown", describeAck(input.type, ack)); +} +function isExplicitRejection(ack) { + return ack.status === "rejected" || ack.status === "failed" || ack.status === void 0; +} +function abortDescription(signal, fallback) { + const reason = signal.reason; + return reason instanceof Error ? reason.message : typeof reason === "string" ? reason : fallback; +} +function errorDescription(err) { + return err instanceof Error ? err.message : String(err); +} +function describeAck(type, ack) { + const status = ack?.reasonCode ?? ack?.status ?? "no session id"; + return `${type} rejected: ${status}${ack?.message !== void 0 ? ` (${ack.message})` : ""}`; +} +function isolationModeFromEnv(env = process.env) { + return env.TEAM_SESSION_ISOLATION === "legacy" ? "legacy" : "child"; +} + +// src/provider/model-catalog.ts +import fs17 from "node:fs"; +import os7 from "node:os"; +import path16 from "node:path"; +function defaultModelConfigPath(homedir = os7.homedir()) { + return path16.join(homedir, ".zcode", "v2", "config.json"); +} +function defaultProviderConfigPath(homedir = os7.homedir()) { + return path16.join(homedir, ".zcode", "v2", "provider_config.json"); +} +function readModelCatalogDetailed(homedir = os7.homedir()) { + const registry2 = readRegistryCatalog(homedir); + if ("catalog" in registry2) { + return { catalog: registry2.catalog, source: "provider-config" }; + } + const registryError = "error" in registry2 ? registry2.error : void 0; + const legacy = readLegacyCatalog(homedir); + return { + ...legacy, + source: "config-json", + ...legacy.error !== void 0 ? { error: registryError !== void 0 ? `${registryError}; ${legacy.error}` : legacy.error } : registryError !== void 0 ? { warning: registryError } : {} + }; +} +function readModelCatalog(homedir = os7.homedir()) { + return readModelCatalogDetailed(homedir).catalog; +} +function findCatalogProvider(catalog, providerId) { + return catalog.providers.find((p) => p.providerId === providerId); +} +function findCatalogModel(catalog, providerId, modelId) { + return findCatalogProvider(catalog, providerId)?.models.find((m) => m.id === modelId); +} +function catalogSupports(catalog, selection) { + const provider = findCatalogProvider(catalog, selection.providerId); + if (provider === void 0 || !provider.enabled) return false; + const model = provider.models.find((m) => m.id === selection.modelId); + return model !== void 0 && model.enabled !== false; +} +function defaultReasoningLevel(catalog, providerId, modelId) { + const model = findCatalogModel(catalog, providerId, modelId); + const variants = model?.reasoning?.variants; + const preferred = model?.reasoning?.defaultVariant; + if (preferred !== void 0 && (variants === void 0 || variants.includes(preferred))) return preferred; + if (variants === void 0) return DEFAULT_REASONING_LEVEL; + return variants.includes(DEFAULT_REASONING_LEVEL) ? DEFAULT_REASONING_LEVEL : variants[0] ?? DEFAULT_REASONING_LEVEL; +} +function applyReasoningDefault(catalog, selection) { + if (selection.reasoningLevel !== void 0) return selection; + return { + ...selection, + reasoningLevel: defaultReasoningLevel(catalog, selection.providerId, selection.modelId) + }; +} +function readRegistryCatalog(homedir) { + const file = defaultProviderConfigPath(homedir); + let doc; + try { + doc = JSON.parse(fs17.readFileSync(file, "utf8")); + } catch (err) { + if (err.code === "ENOENT") return { missing: true }; + return { error: `provider registry unavailable: ${err instanceof Error ? err.message : String(err)}` }; + } + const config3 = doc?.config; + if (config3 === null || typeof config3 !== "object" || Array.isArray(config3)) { + return { error: "provider registry unavailable: config is not an object" }; + } + const cfg = config3; + const order = cfg.providerOrder; + const rules = cfg.providerConfigRules?.providerRules; + if (!Array.isArray(order) || !Array.isArray(rules)) { + return { error: "provider registry unavailable: providerOrder/providerRules is not an array" }; + } + const ruleById = /* @__PURE__ */ new Map(); + for (const raw of rules) { + if (raw === null || typeof raw !== "object" || Array.isArray(raw)) continue; + const rule = raw; + const providerId = nonEmpty(rule.providerId); + if (providerId !== void 0) ruleById.set(providerId, rule); + } + const modelRules = registryModelRules(cfg); + const legacyReasoning = readLegacyReasoning(homedir); + const providers = []; + const seen = /* @__PURE__ */ new Set(); + for (const rawId of order) { + const providerId = nonEmpty(rawId); + if (providerId === void 0 || seen.has(providerId)) continue; + seen.add(providerId); + const rule = ruleById.get(providerId); + const ruleConfig = recordOf(rule?.config); + const models = []; + const modelSeen = /* @__PURE__ */ new Set(); + for (const rawModel of arrayOf(ruleConfig?.modelOrder)) { + const id = nonEmpty(rawModel); + if (id === void 0 || modelSeen.has(id)) continue; + modelSeen.add(id); + const ruleConfigForModel = modelRules.get(modelKey(providerId, id)); + const enabled = ruleConfigForModel?.enabled !== false; + const reasoning = legacyReasoning.get(modelKey(providerId, id)) ?? registryReasoning(ruleConfigForModel); + models.push({ + id, + enabled, + ...reasoning !== void 0 ? { reasoning } : {} + }); + } + providers.push({ + providerId, + name: nonEmpty(rule?.providerName) ?? providerId, + // api.type 是协议族(anthropic/openai-responses…)——只取该字符串,绝不带 baseUrl。 + kind: nonEmpty(recordOf(ruleConfig?.api)?.type) ?? "unknown", + enabled: true, + models + }); + } + return { catalog: { providers } }; +} +function registryModelRules(cfg) { + const rules = cfg.modelConfigRules?.providerModelRules; + const out = /* @__PURE__ */ new Map(); + for (const raw of arrayOf(rules)) { + if (raw === null || typeof raw !== "object" || Array.isArray(raw)) continue; + const rule = raw; + const providerId = nonEmpty(rule.providerId); + const modelId = nonEmpty(rule.modelId); + if (providerId === void 0 || modelId === void 0) continue; + out.set(modelKey(providerId, modelId), recordOf(rule.config) ?? {}); + } + return out; +} +function registryReasoning(rule) { + const specs = recordOf(rule?.optionSpecs); + const level = recordOf(specs?.reasoningLevel); + return catalogReasoning({ variants: level?.values }); +} +function readLegacyCatalog(homedir) { + const file = defaultModelConfigPath(homedir); + const doc = readJsonOrUndefined(file); + if ("error" in doc) { + return { catalog: { providers: [] }, error: `model catalog unavailable: ${doc.error}` }; + } + const rawProviders = doc.value?.provider; + if (rawProviders === null || typeof rawProviders !== "object" || Array.isArray(rawProviders)) { + return { catalog: { providers: [] }, error: "model catalog unavailable: config.provider is not an object" }; + } + const providers = []; + for (const [providerId, raw] of Object.entries(rawProviders)) { + if (providerId.length === 0 || raw === null || typeof raw !== "object" || Array.isArray(raw)) continue; + const record2 = raw; + const enabled = record2.enabled !== false; + const disabledReason = enabled ? void 0 : nonEmpty(record2.systemDisabledReason) ?? "disabled"; + providers.push({ + providerId, + name: nonEmpty(record2.name) ?? providerId, + kind: nonEmpty(record2.kind) ?? "unknown", + enabled, + ...disabledReason !== void 0 ? { disabledReason } : {}, + models: legacyModels(record2.models) + }); + } + return { catalog: { providers } }; +} +function legacyModels(raw) { + const models = []; + if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) { + for (const [id, value] of Object.entries(raw)) { + const model = legacyModel(id, value); + if (model !== void 0) models.push(model); + } + return models; + } + if (Array.isArray(raw)) { + for (const value of raw) { + const id = nonEmpty(value?.id); + const model = legacyModel(id ?? "", value); + if (model !== void 0) models.push(model); + } + } + return models; +} +function legacyModel(id, raw) { + if (id.length === 0) return void 0; + const record2 = raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw : {}; + const reasoning = catalogReasoning(record2.reasoning); + return { id, enabled: true, ...reasoning !== void 0 ? { reasoning } : {} }; +} +function readLegacyReasoning(homedir) { + const out = /* @__PURE__ */ new Map(); + const doc = readJsonOrUndefined(defaultModelConfigPath(homedir)); + if ("error" in doc) return out; + const rawProviders = doc.value?.provider; + if (rawProviders === null || typeof rawProviders !== "object" || Array.isArray(rawProviders)) return out; + for (const [providerId, raw] of Object.entries(rawProviders)) { + const record2 = recordOf(raw); + const models = recordOf(record2?.models); + if (models === void 0) continue; + for (const [modelId, modelRaw] of Object.entries(models)) { + const reasoning = catalogReasoning(recordOf(modelRaw)?.reasoning); + if (reasoning !== void 0) out.set(modelKey(providerId, modelId), reasoning); + } + } + return out; +} +function catalogReasoning(raw) { + if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return void 0; + const record2 = raw; + if (record2.enabled === false) return void 0; + if (!Array.isArray(record2.variants)) return void 0; + const variants = [...new Set(record2.variants.map(nonEmpty).filter((v) => v !== void 0))]; + if (variants.length === 0) return void 0; + const defaultVariant = nonEmpty(record2.defaultVariant); + return { + variants, + ...defaultVariant !== void 0 && variants.includes(defaultVariant) ? { defaultVariant } : {} + }; +} +function modelKey(providerId, modelId) { + return `${providerId}\0${modelId}`; +} +function recordOf(value) { + return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0; +} +function arrayOf(value) { + return Array.isArray(value) ? value : []; +} +function readJsonOrUndefined(file) { + try { + return { value: JSON.parse(fs17.readFileSync(file, "utf8")) }; + } catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } +} +function nonEmpty(value) { + if (typeof value !== "string") return void 0; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : void 0; +} + +// src/provider/resume-provider.ts +var LEAD_DELIVERY_VIA_HOOKS = true; +var DEFAULT_MODEL_RETRY_BACKOFF_MS = [5e3, 15e3, 3e4]; +var ResumePerTurnProvider = class { + constructor(opts) { + this.opts = opts; + this.teamDir = path17.join(opts.dataRoot, "teams", safeDir(opts.teamId)); + this.cwd = opts.cwd ?? process.env.TEAM_PROJECT_DIR ?? process.cwd(); + this.reader = new TranscriptReader({ ...opts.dbPath !== void 0 ? { dbPath: opts.dbPath } : {} }); + this.zcode = opts.zcode ?? resolveZcodeBin(); + this.drainPolicy = opts.drainPolicy ?? drainPolicyFromEnv(); + this.termGraceMs = opts.termGraceMs ?? 3e3; + this.firstTurnTimeoutMs = opts.firstTurnTimeoutMs ?? 12e4; + this.deliverConfirmMs = opts.deliverConfirmMs ?? 15e3; + this.watcherIntervalMs = opts.watcherIntervalMs ?? 500; + this.relaunchBackoffMs = opts.relaunchBackoffMs ?? 2e3; + this.sessionIsolation = opts.sessionIsolation ?? isolationModeFromEnv(); + this.leadWakeMinIdleMs = opts.leadWakeMinIdleMs ?? Number(process.env.TEAM_WAKE_LEAD_MIN_IDLE_MS ?? 3e4); + this.modelRetryBackoffMs = opts.modelRetryBackoffMs !== void 0 && opts.modelRetryBackoffMs.length > 0 ? opts.modelRetryBackoffMs : DEFAULT_MODEL_RETRY_BACKOFF_MS; + this.breeder = opts.breeder ?? new AppServerSessionBreeder({ + zcode: this.zcode, + ...opts.dbPath !== void 0 ? { dbPath: opts.dbPath } : {}, + log: (record2) => this.log(record2), + now: opts.now ?? Date.now + }); + this.now = opts.now ?? Date.now; + this.modelCatalog = opts.modelCatalog ?? (() => readModelCatalog()); + this.sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + this.log = opts.log ?? (() => { + }); + } + LEAD_DELIVERY_VIA_HOOKS = LEAD_DELIVERY_VIA_HOOKS; + teamDir; + cwd; + reader; + zcode; + drainPolicy; + termGraceMs; + firstTurnTimeoutMs; + deliverConfirmMs; + watcherIntervalMs; + relaunchBackoffMs; + sessionIsolation; + leadWakeMinIdleMs; + modelRetryBackoffMs; + breeder; + modelCatalog; + now; + sleep; + log; + boundaryListeners = /* @__PURE__ */ new Set(); + watcherTimer = null; + adoptedPids = /* @__PURE__ */ new Set(); + watcherBusy = false; + leadReceiptsMtimeMs = null; + lastLaunchFailureAt = 0; + pendingLookup = null; + closed = false; + generation = 0; + generationAbort = new AbortController(); + backgroundDeferred = false; + /** 失败记录变化监听(0.4.1:host 接线 → roster.notifyStatusChanged 刷新成员展示)。 */ + modelFailureListeners = /* @__PURE__ */ new Set(); + // ---------------------------------------------------------------- 边界与接线 + /** 协调者接线(host.serve):轮次边界监听 + pending 合并查询(mailbox 派生) + * + 模型失败记录变化通知(0.4.1:后台续跑失败 → 成员展示立即刷新)。 */ + bind(hooks) { + this.boundaryListeners.add(hooks.onBoundary); + this.pendingLookup = hooks.pendingLookup; + if (hooks.onModelFailureChanged !== void 0) { + this.modelFailureListeners.add(hooks.onModelFailureChanged); + } + } + notifyModelFailureChanged() { + for (const listener of this.modelFailureListeners) { + try { + listener(); + } catch (err) { + this.log({ ts: iso(this.now()), kind: "model-failure-listener-error", error: errText2(err) }); + } + } + } + /** + * spawn 前置校验(0.4.1):Lead 模型不可继承 → 抛错。roster 在**登记成员之前**调用, + * 可提前识别的配置错误不产生 provisioning 成员、不占成员名、不建隐藏子会话。 + * 供给阶段仍复检(resolveLeadInheritance 在 startContinuable 内照跑)——预检后配置可能变化。 + * legacy 隔离模式无继承语义 → 恒通过。 + */ + preflightMemberModel() { + if (this.sessionIsolation !== "child") return; + this.resolveLeadInheritance(); + } + /** 仅在当前代次内写 origin;旧进度回调/后台恢复只读,不覆盖新代次。 */ + writeCurrentOrigin(paths, origin) { + if (this.closed || this.generationAbort.signal.aborted) return false; + writeOrigin(paths, origin); + return true; + } + /** 协调者启动纳管:孤儿轮次定案/再收养 + drain 标记处置 + lead 回执折叠(T4.4/触发点②)。 */ + adoptOrphans() { + const finalized = []; + const adopted = []; + for (const memberId of listMembers(this.teamDir)) { + const paths = memberPaths(this.teamDir, memberId); + this.handleDrainMarker(paths); + for (const turn of listTurns(paths.runDir)) { + if (turn.status !== "running" && turn.status !== "starting") continue; + if (turn.pid === null) { + const receipt = readSpawnReceipt(path17.join(paths.runDir, `${turn.turnId}.spawn.json`)); + if (receipt?.pid !== void 0) { + writeTurn(paths.runDir, { ...turn, pid: receipt.pid, pgid: receipt.pid, status: "running" }); + this.adoptedPids.add(receipt.pid); + adopted.push(turn.turnId); + } + continue; + } + if (this.finalizeIfDead(memberId, turn)) { + finalized.push(turn.turnId); + } else if (turn.pid !== null) { + this.adoptedPids.add(turn.pid); + adopted.push(turn.turnId); + } + } + } + this.foldLeadReceipts(true); + this.startWatcher(); + return { finalized, adopted }; + } + /** 协调者每次获锁都启用新代次;旧 watcher/恢复回调不能借用下一次获锁的权限。 */ + activateGeneration() { + this.generation += 1; + this.generationAbort = new AbortController(); + this.closed = false; + this.backgroundDeferred = true; + return this.generationAbort.signal; + } + generationIsCurrent(generation) { + return generation === this.generation && !this.closed; + } + /** 协调者关闭:先撤销本代次,再停 watcher;轮次进程不杀。 */ + detach() { + this.closed = true; + this.generationAbort.abort(new Error("coordinator generation revoked")); + if (this.watcherTimer !== null) { + clearInterval(this.watcherTimer); + this.watcherTimer = null; + } + this.adoptedPids.clear(); + } + emitBoundary(event) { + for (const listener of this.boundaryListeners) { + try { + listener(event); + } catch (err) { + this.log({ ts: iso(this.now()), kind: "boundary-listener-error", memberId: event.memberId, error: errText2(err) }); + } + } + } + startWatcher() { + if (this.watcherTimer !== null || this.closed || this.backgroundDeferred) return; + const generation = this.generation; + const timer = setInterval(() => { + if (!this.generationIsCurrent(generation)) return; + void this.watchTick(generation).catch((err) => { + this.log({ ts: iso(this.now()), kind: "watcher-error", error: errText2(err) }); + }); + }, this.watcherIntervalMs); + timer.unref?.(); + this.watcherTimer = timer; + } + async watchTick(generation = this.generation) { + if (this.watcherBusy || !this.generationIsCurrent(generation)) return; + const signal = this.generationAbort.signal; + this.watcherBusy = true; + try { + for (const memberId of listMembers(this.teamDir)) { + if (!this.generationIsCurrent(generation)) return; + const paths = memberPaths(this.teamDir, memberId); + const turnId = readCurrentTurnId(paths); + if (turnId === void 0) continue; + const turn = readTurn(paths.runDir, turnId); + if (turn === void 0) continue; + if (turn.status === "running" || turn.status === "starting") { + if (turn.interruptRequestedAt !== void 0) { + const dead = await killProcessGroup(turn.pgid, this.termGraceMs, signal); + if (!this.generationIsCurrent(generation)) return; + if (dead) { + const landed = turn.sessionId !== null && this.reader.hasUserText(turn.sessionId, turn.promptText); + writeTurn(paths.runDir, { + ...turn, + status: "interrupted", + exitedAt: iso(this.now()), + landed + }); + this.emitBoundary({ + memberId, + turnId: turn.turnId, + landedMessageIds: landed ? turn.messageIds : [], + carriedMessageIds: turn.messageIds + }); + } + continue; + } + if (this.generationIsCurrent(generation)) this.finalizeIfDead(memberId, turn); + } + } + if (this.generationIsCurrent(generation)) this.foldLeadReceipts(false); + } finally { + this.watcherBusy = false; + } + } + /** 轮次进程已死 → 定案(landed 实查)+ 边界事件;返回是否已定案。 */ + finalizeIfDead(memberId, turn) { + if (turn.pid === null) return false; + if (pidAlive(turn.pid)) { + this.adoptedPids.add(turn.pid); + return false; + } + const landed = turn.sessionId !== null && this.reader.hasUserText(turn.sessionId, turn.promptText); + const next = { + ...turn, + status: "exited", + exitedAt: iso(this.now()), + landed + }; + const paths = memberPaths(this.teamDir, memberId); + writeTurn(paths.runDir, next); + this.adoptedPids.delete(turn.pid ?? -1); + this.log({ + ts: iso(this.now()), + kind: "turn-exit", + teamId: this.opts.teamId, + memberId, + turnId: turn.turnId, + landed, + messageIds: turn.messageIds + }); + if (!landed && turn.messageIds.length > 0) { + this.lastLaunchFailureAt = this.now(); + } + this.emitBoundary({ + memberId, + turnId: turn.turnId, + landedMessageIds: landed ? turn.messageIds : [], + carriedMessageIds: turn.messageIds + }); + return true; + } + /** lead 回执折叠:回执文件变化 → 边界事件(runtime → mailbox.observeDelivery → markDelivered)。 */ + foldLeadReceipts(force) { + const paths = memberPaths(this.teamDir, this.opts.teamId); + let mtimeMs = null; + try { + mtimeMs = fs18.statSync(paths.receiptsFile).mtimeMs; + } catch { + mtimeMs = null; + } + if (!force && mtimeMs === this.leadReceiptsMtimeMs) return; + this.leadReceiptsMtimeMs = mtimeMs; + if (mtimeMs === null) return; + const ids = [...receiptMessageIds(paths)]; + if (ids.length === 0) return; + this.emitBoundary({ memberId: this.opts.teamId, landedMessageIds: ids, carriedMessageIds: ids }); + } + // ---------------------------------------------------------------- TeammateProvider + prepareContinuable(args) { + const paths = memberPaths(this.teamDir, args.memberId); + const existing = readOrigin(paths); + if (existing !== void 0) { + if (existing.requestId === args.requestId) return; + throw new Error(`member ${args.memberId} already has a creation intent`); + } + const prompt = args.context === "fork" ? buildForkFirstPrompt(this.reader, this.opts.teamId, args.firstPrompt).prompt : args.firstPrompt; + const request = args.requestId; + const anchorSessionId = `sess_team_${request.replace(/[^A-Za-z0-9_-]/g, "")}`; + writeOrigin(paths, { + teamId: args.teamId, + memberId: args.memberId, + name: args.name, + provider: args.context === "fork" ? "fork" : "spawn", + mode: "continuable", + context: args.context, + createdAt: iso(this.now()), + cwd: this.cwd, + firstPromptText: prompt, + firstPromptSha256: sha256(prompt), + sessionId: null, + initialUserMessageAccepted: false, + sessionIsolation: this.sessionIsolation, + ...this.sessionIsolation === "child" ? { + anchorSessionId, + logicalParentSessionId: args.teamId, + sessionKind: "selection_side_chat", + hostAnchorConfirmed: false + } : { sessionKind: "interactive" }, + requestId: args.requestId, + ...this.sessionIsolation === "child" ? { anchorCommandId: `team-anchor-${request}`, childCommandId: `team-child-${request}` } : {}, + creationPending: true, + creationDiagnostic: "creation intent persisted; awaiting host confirmation", + confirmationAttempts: 0, + confirmationDeadlineAt: iso(this.now() + this.firstTurnTimeoutMs) + }); + } + async resumeContinuable(memberId, signal) { + const paths = memberPaths(this.teamDir, memberId); + const origin = readOrigin(paths); + if (origin === void 0 || origin.requestId === void 0) { + throw new ProvisioningPending("\u521B\u5EFA\u610F\u56FE\u7F3A\u5931\uFF0C\u65E0\u6CD5\u81EA\u52A8\u6062\u590D\uFF1B\u4E0D\u4F1A\u91CD\u65B0\u751F\u6210\u521B\u5EFA\u8BF7\u6C42"); + } + if (origin.confirmationStopped === true) { + throw new ProvisioningPending("\u521B\u5EFA\u7ED3\u679C\u5F85\u786E\u8BA4\uFF0C\u81EA\u52A8\u6062\u590D\u9884\u7B97\u5DF2\u8017\u5C3D\uFF1B\u8BF7\u7531 Lead \u63A5\u7BA1"); + } + return this.startContinuable({ + teamId: origin.teamId, + memberId, + name: origin.name, + description: "", + firstPrompt: origin.firstPromptText, + context: origin.context, + requestId: origin.requestId, + ...signal !== void 0 ? { signal } : {} + }); + } + noteProvisioningRecovery(memberId) { + const paths = memberPaths(this.teamDir, memberId); + let origin; + try { + origin = readOrigin(paths); + } catch { + return true; + } + if (origin === void 0 || origin.confirmationStopped === true) return true; + const attempts = (origin.confirmationAttempts ?? 0) + 1; + const stopped = attempts >= 3 || origin.confirmationDeadlineAt !== void 0 && Date.parse(origin.confirmationDeadlineAt) <= this.now(); + this.writeCurrentOrigin(paths, { + ...origin, + confirmationAttempts: attempts, + ...stopped ? { confirmationStopped: true, creationDiagnostic: "\u7ED3\u679C\u5F85\u786E\u8BA4\uFF1B\u81EA\u52A8\u6062\u590D\u5DF2\u505C\u6B62\uFF0C\u8BF7\u7531 Lead \u63A5\u7BA1" } : {} + }); + return stopped; + } + startBackground() { + this.backgroundDeferred = false; + this.startWatcher(); + } + async startContinuable(args) { + const generation = this.generation; + if (!this.generationIsCurrent(generation)) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4FDD\u7559\u521B\u5EFA\u610F\u56FE\u4F9B\u63A5\u4EFB\u8005\u786E\u8BA4"); + } + if (args.teamId !== this.opts.teamId) { + throw new Error(`provider serves team ${this.opts.teamId} but spawn targets ${args.teamId}`); + } + const paths = memberPaths(this.teamDir, args.memberId); + const persistedOrigin = readOrigin(paths); + if (persistedOrigin === void 0 || persistedOrigin.requestId !== args.requestId) { + throw new ProvisioningPending("\u521B\u5EFA\u610F\u56FE\u7F3A\u5931\u6216\u4E0D\u5339\u914D\uFF1B\u4E0D\u4F1A\u91CD\u65B0\u751F\u6210\u521B\u5EFA\u8BF7\u6C42"); + } + const persisted = persistedOrigin; + if (persisted.confirmationStopped === true) { + throw new ProvisioningPending("\u7ED3\u679C\u5F85\u786E\u8BA4\uFF0C\u81EA\u52A8\u6062\u590D\u9884\u7B97\u5DF2\u8017\u5C3D\uFF1B\u8BF7\u7531 Lead \u63A5\u7BA1"); + } + const prompt = persisted.firstPromptText; + const existingTurnId = readCurrentTurnId(paths); + const existingTurn = existingTurnId === void 0 ? listTurns(paths.runDir).findLast((turn2) => turn2.kind === "first") : readTurn(paths.runDir, existingTurnId); + if (existingTurn !== void 0 && existingTurn.memberId !== args.memberId) { + throw new ProvisioningPending("\u73B0\u6709 turn \u4E0E\u6210\u5458\u610F\u56FE\u4E0D\u5339\u914D\uFF1B\u505C\u6B62\u81EA\u52A8\u6062\u590D"); + } + if (existingTurn?.kind === "first") { + if (existingTurn.promptText !== prompt) { + throw new ProvisioningPending("\u73B0\u6709\u9996\u8F6E\u8F93\u5165\u4E0E origin \u4E0D\u4E00\u81F4\uFF1B\u505C\u6B62\u81EA\u52A8\u6062\u590D"); + } + if (existingTurn.status === "exited" || existingTurn.status === "failed" || existingTurn.status === "spawn-error" || existingTurn.status === "interrupted") { + throw new ProvisioningPending("\u5DF2\u6709\u9996\u8F6E\u7EC8\u6001\u8BB0\u5F55\uFF1B\u4E0D\u4F1A\u81EA\u52A8\u91CD\u590D\u542F\u52A8"); + } + const persistedWithSession = persisted.sessionId === null && existingTurn.sessionId !== null ? { ...persisted, sessionId: existingTurn.sessionId } : persisted; + try { + const accepted = await this.awaitFirstAccept({ + paths, + origin: persistedWithSession, + turn: existingTurn, + spawnT0: Date.parse(existingTurn.startedAt), + generation, + ...args.signal !== void 0 ? { signal: args.signal } : {} + }); + return { memberId: args.memberId, accepted: accepted !== null }; + } catch (err) { + if (err instanceof ProvisioningPending) throw err; + throw new ProvisioningPending("\u5DF2\u6709\u9996\u8F6E\u542F\u52A8\u610F\u56FE\uFF0C\u7ED3\u679C\u5F85\u786E\u8BA4\uFF1B\u4E0D\u4F1A\u91CD\u590D\u542F\u52A8"); + } + } + const inheritedSelection = this.sessionIsolation === "child" ? this.resolveLeadInheritance() : void 0; + let bred = null; + if (this.sessionIsolation === "child") { + try { + bred = await this.breeder.createChild({ + teamId: this.opts.teamId, + workspacePath: this.cwd, + ...inheritedSelection !== void 0 ? { modelSelection: inheritedSelection } : {}, + ...persisted.anchorCommandId !== void 0 ? { anchorCommandId: persisted.anchorCommandId } : {}, + ...persisted.childCommandId !== void 0 ? { childCommandId: persisted.childCommandId } : {}, + ...persisted.anchorSessionId !== void 0 ? { anchorSessionId: persisted.anchorSessionId } : {}, + ...persisted.hostAnchorConfirmed === true || persisted.sessionId !== null ? { recoveryEvidence: true } : {}, + ...args.signal !== void 0 ? { signal: args.signal } : {}, + onProgress: (progress) => { + if (!this.generationIsCurrent(generation)) return; + const latest = readOrigin(paths) ?? persisted; + if (latest.requestId !== args.requestId) return; + return this.writeCurrentOrigin(paths, { + ...latest, + ...progress.anchorSessionId !== void 0 ? { anchorSessionId: progress.anchorSessionId, hostAnchorConfirmed: true } : {}, + ...progress.childSessionId !== void 0 ? { sessionId: progress.childSessionId } : {}, + creationDiagnostic: progress.stage + }); + } + }); + } catch (err) { + if (!this.generationIsCurrent(generation)) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4FDD\u7559\u5BBF\u4E3B\u8BC1\u636E\u4F9B\u63A5\u4EFB\u8005\u786E\u8BA4"); + } + const message = err instanceof Error ? err.message : String(err); + if (err.code === "outcome-unknown") { + if (args.signal?.aborted && !this.generationAbort.signal.aborted) throw err; + throw new ProvisioningPending("\u5BBF\u4E3B\u521B\u5EFA\u7ED3\u679C\u5F85\u786E\u8BA4\uFF1B\u4E0D\u4F1A\u91CD\u65B0\u751F\u6210\u521B\u5EFA\u8BF7\u6C42"); + } + if (inheritedSelection !== void 0 && /inherited model/.test(message)) { + this.recordModelFailure( + paths, + args.memberId, + new ModelInheritanceError(`\u6210\u5458\u6A21\u578B\u65E0\u6CD5\u7EE7\u627F\uFF1A${message}`, inheritedSelection), + [], + classifyApplyFailure(message) + ); + } + throw err; + } + } + if (!this.generationIsCurrent(generation)) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4FDD\u7559\u5BBF\u4E3B\u8BC1\u636E\u4F9B\u63A5\u4EFB\u8005\u786E\u8BA4"); + } + const spawnCwd = bred?.workspacePath ?? persisted.cwd; + const origin = { + ...persisted, + cwd: spawnCwd, + sessionId: bred?.childSessionId ?? persisted.sessionId, + initialUserMessageAccepted: persisted.initialUserMessageAccepted, + ...bred?.appliedModel !== void 0 ? { modelSelection: bred.appliedModel, modelSource: "inherited" } : {}, + ...bred !== null ? { anchorSessionId: bred.anchorSessionId } : {} + }; + if (!this.writeCurrentOrigin(paths, origin)) { + throw new ProvisioningPending("\u521B\u5EFA\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4FDD\u7559\u5BBF\u4E3B\u8BC1\u636E\u4F9B\u63A5\u4EFB\u8005\u786E\u8BA4\uFF0C\u4E0D\u542F\u52A8\u9996\u8F6E"); + } + const spawnT0 = this.now(); + const turn = await this.launchTurn({ + paths, + memberId: args.memberId, + name: args.name, + kind: "first", + messageIds: [], + promptText: prompt, + sessionId: bred?.childSessionId ?? null, + resume: bred !== null, + cwd: spawnCwd, + // createChild 刚把继承选择应用进子会话(0.4.1 验收:首轮不重复应用同一选择)。 + modelJustApplied: bred?.appliedModel, + ...args.signal !== void 0 ? { signal: args.signal } : {} + }); + this.startWatcher(); + try { + const sessionId = await this.awaitFirstAccept({ + paths, + origin, + turn, + spawnT0, + generation, + signal: args.signal + }); + return { memberId: args.memberId, accepted: sessionId !== null }; + } catch (err) { + if (args.signal?.aborted && !this.generationAbort.signal.aborted) throw args.signal.reason ?? err; + if (err instanceof ProvisioningPending) throw err; + this.log({ ts: iso(this.now()), kind: "first-probe-error", memberId: args.memberId, error: errText2(err) }); + throw new ProvisioningPending("\u9996\u8F6E\u6301\u4E45\u63A5\u6536\u7ED3\u679C\u5F85\u786E\u8BA4\uFF1B\u4E0D\u4F1A\u91CD\u590D\u542F\u52A8"); + } + } + /** 首轮持久接收探针:session id 认领(hook 领地优先,db 目录+首条用户文本兜底)+ 落库确认。 */ + async awaitFirstAccept(args) { + const { paths, origin, turn, spawnT0 } = args; + const deadline = spawnT0 + this.firstTurnTimeoutMs; + let sessionId = origin.sessionId ?? this.claimedSessionId(origin.memberId); + for (; ; ) { + if (!this.generationIsCurrent(args.generation)) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u9996\u8F6E\u7ED3\u679C\u5F85\u63A5\u4EFB\u8005\u786E\u8BA4"); + } + if (args.signal?.aborted && !this.generationAbort.signal.aborted) throw args.signal.reason ?? new Error("aborted"); + sessionId ??= this.claimedSessionId(origin.memberId); + if (sessionId === null) { + const exclude = this.claimedSessionsExcluding(origin.memberId); + const found = this.reader.findSessionByFirstPrompt({ + cwd: origin.cwd, + firstPrompt: origin.firstPromptText, + sinceMs: spawnT0, + ...exclude.size > 0 ? { excludeSessionIds: exclude } : {} + }); + if (found !== void 0) sessionId = found; + } + if (sessionId !== null) { + let landed; + try { + landed = this.reader.hasUserText(sessionId, origin.firstPromptText); + } catch (err) { + throw new ProvisioningPending(`\u9996\u8F6E\u63A5\u6536\u6682\u4E0D\u53EF\u786E\u8BA4\uFF1A${errText2(err)}`); + } + if (landed) { + const nextOrigin = { + ...readOrigin(paths) ?? origin, + sessionId, + initialUserMessageAccepted: true, + creationPending: false, + creationDiagnostic: void 0 + }; + if (!this.writeCurrentOrigin(paths, nextOrigin)) { + throw new ProvisioningPending("\u9996\u8F6E\u5DF2\u88AB\u5BBF\u4E3B\u786E\u8BA4\uFF0C\u4F46\u65E7\u4EE3\u6B21\u4E0D\u5F97\u8986\u76D6\u6062\u590D\u72B6\u6001"); + } + const current = readTurn(paths.runDir, turn.turnId) ?? turn; + writeTurn(paths.runDir, { ...current, sessionId, landed: true }); + this.writeTeammateMapping(sessionId, nextOrigin); + this.log({ + ts: iso(this.now()), + kind: "first-accepted", + teamId: this.opts.teamId, + memberId: origin.memberId, + turnId: turn.turnId, + sessionId, + ms: this.now() - spawnT0 + }); + return sessionId; + } + } + const turnNow = readTurn(paths.runDir, turn.turnId); + const pid = turnNow?.pid ?? turn.pid; + if (pid === null) { + throw new ProvisioningPending("\u5DF2\u6709\u542F\u52A8\u610F\u56FE\u4F46\u5C1A\u65E0 PID/\u56DE\u6267\u786E\u8BA4\uFF1B\u4FDD\u6301\u5F85\u6062\u590D\uFF0C\u4E0D\u91CD\u590D\u542F\u52A8"); + } + if (!pidAlive(pid)) { + this.log({ + ts: iso(this.now()), + kind: "first-not-accepted", + teamId: this.opts.teamId, + memberId: origin.memberId, + turnId: turn.turnId, + sessionId + }); + return null; + } + if (this.now() >= deadline) { + this.log({ + ts: iso(this.now()), + kind: "first-probe-timeout", + teamId: this.opts.teamId, + memberId: origin.memberId, + turnId: turn.turnId + }); + throw new ProvisioningPending("\u9996\u8F6E\u63A5\u6536\u7ED3\u679C\u5F85\u786E\u8BA4\uFF1B\u65E7 turn \u53EF\u80FD\u4ECD\u5728\u6267\u884C\uFF0C\u4E0D\u4F1A\u91CD\u590D\u542F\u52A8"); + } + await this.sleep(150); + } + } + async deliver(args) { + const debug = process.env.TEAM_DEBUG_DELIVERY === "1"; + const generation = this.generation; + const paths = memberPaths(this.teamDir, args.memberId); + const origin = readOrigin(paths); + if (origin === void 0) { + if (debug) this.log({ ts: iso(this.now()), kind: "deliver-deferred", memberId: args.memberId, reason: "no-origin" }); + return "queued"; + } + if (this.containsMessage(args.memberId, args.messageId)) return "accepted"; + const current = this.currentRunningTurn(paths, true); + if (current !== null) { + if (debug) this.log({ ts: iso(this.now()), kind: "deliver-deferred", memberId: args.memberId, reason: "running", turnId: current.turnId }); + return "queued"; + } + const sessionId = origin.sessionId ?? this.resolveSessionId(origin); + if (sessionId === null) { + if (debug) this.log({ ts: iso(this.now()), kind: "deliver-deferred", memberId: args.memberId, reason: "session-unsettled" }); + return "queued"; + } + if (this.now() - this.lastLaunchFailureAt < this.relaunchBackoffMs && this.lastLaunchFailureAt > 0) { + if (debug) this.log({ ts: iso(this.now()), kind: "deliver-deferred", memberId: args.memberId, reason: "launch-backoff" }); + return "queued"; + } + const batchRaw = this.pendingLookup !== null ? this.pendingLookup(args.memberId) : [{ messageId: args.messageId, framedJson: args.framedMessage }]; + const batch = batchRaw.filter((item) => !this.containsMessage(args.memberId, item.messageId)); + if (batch.length === 0) return "accepted"; + const { promptText } = renderFramedBatch(batch); + const turn = await this.launchTurn({ + paths, + memberId: args.memberId, + name: origin.name, + kind: "deliver", + messageIds: batch.map((item) => item.messageId), + promptText, + sessionId, + resume: true, + cwd: origin.cwd + }).catch((err) => { + if (err instanceof ModelSyncSuppressedError || err instanceof ProvisioningPending) { + if (debug) { + this.log({ ts: iso(this.now()), kind: "deliver-deferred", memberId: args.memberId, reason: "model-sync-suppressed" }); + } + return null; + } + throw err; + }); + if (turn === null) return "queued"; + this.startWatcher(); + const deadline = this.now() + this.deliverConfirmMs; + for (; ; ) { + if (!this.generationIsCurrent(generation)) return "queued"; + if (this.reader.hasUserText(sessionId, promptText)) { + const current2 = readTurn(paths.runDir, turn.turnId) ?? turn; + writeTurn(paths.runDir, { ...current2, landed: true }); + this.log({ + ts: iso(this.now()), + kind: "deliver-landed", + teamId: this.opts.teamId, + memberId: args.memberId, + turnId: turn.turnId, + messageIds: current2.messageIds + }); + return "accepted"; + } + const turnNow = readTurn(paths.runDir, turn.turnId); + const pid = turnNow?.pid ?? turn.pid; + if (pid === null || !pidAlive(pid)) { + this.lastLaunchFailureAt = this.now(); + return "queued"; + } + if (this.now() >= deadline) { + return "queued"; + } + await this.sleep(150); + } + } + async interrupt(args) { + const generation = this.generation; + const signal = this.generationAbort.signal; + if (!this.generationIsCurrent(generation) || signal.aborted) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4E2D\u65AD\u7ED3\u679C\u5F85\u786E\u8BA4"); + } + const paths = memberPaths(this.teamDir, args.memberId); + const current = this.currentRunningTurn(paths, true); + const previousStatus = current !== null ? "running" : "inactive"; + if (current === null) return { previousStatus }; + if (current.pid === null) { + throw new ProvisioningPending("\u6210\u5458\u542F\u52A8\u7ED3\u679C\u5F85\u786E\u8BA4\uFF0C\u6682\u4E0D\u80FD\u5B89\u5168\u4E2D\u65AD\uFF1B\u65E7\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF0C\u8BF7\u52FF\u91CD\u590D\u53D1\u9001\u3002"); + } + writeTurn(paths.runDir, { ...current, interruptRequestedAt: iso(this.now()) }); + let dead; + try { + dead = await killProcessGroup(current.pgid, this.termGraceMs, signal); + } catch (err) { + if (this.generationIsCurrent(generation) && !signal.aborted) writeTurn(paths.runDir, { ...current }); + throw err; + } + if (!this.generationIsCurrent(generation) || signal.aborted) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4E2D\u65AD\u7ED3\u679C\u5F85\u786E\u8BA4"); + } + if (!dead) { + writeTurn(paths.runDir, { ...current }); + throw new Error(`interrupt failed: process group ${String(current.pgid)} is still alive`); + } + const finalTurn = readTurn(paths.runDir, current.turnId) ?? current; + const landed = finalTurn.sessionId !== null && this.reader.hasUserText(finalTurn.sessionId, finalTurn.promptText); + writeTurn(paths.runDir, { ...finalTurn, status: "interrupted", exitedAt: iso(this.now()), landed }); + this.log({ + ts: iso(this.now()), + kind: "interrupt", + teamId: this.opts.teamId, + memberId: args.memberId, + turnId: current.turnId, + previousStatus, + dead, + landed + }); + this.emitBoundary({ + memberId: args.memberId, + turnId: current.turnId, + landedMessageIds: landed ? current.messageIds : [], + carriedMessageIds: current.messageIds + }); + return { previousStatus }; + } + async drain(args) { + if (this.closed || this.generationAbort.signal.aborted) { + throw new Error("coordinator generation revoked; drain requires current ownership"); + } + const generation = this.generation; + const signal = this.generationAbort.signal; + const memberIds = listMembers(this.teamDir); + if (this.drainPolicy === "keep") { + for (const memberId of memberIds) { + const paths = memberPaths(this.teamDir, memberId); + const current = readCurrentTurnId(paths); + if (current === void 0) continue; + writeJsonAtomic(paths.drainMarkerFile, { policy: "keep", requestedAt: iso(this.now()), turnId: current }); + } + this.log({ ts: iso(this.now()), kind: "drain-keep", teamId: this.opts.teamId, members: memberIds.length }); + return; + } + const grace = Math.max(200, Math.min(this.termGraceMs, Math.floor(args.timeoutMs * 0.6))); + const failures = []; + for (const memberId of memberIds) { + if (!this.generationIsCurrent(generation) || signal.aborted) { + throw new Error("coordinator generation revoked; drain requires current ownership"); + } + const paths = memberPaths(this.teamDir, memberId); + const turnId = readCurrentTurnId(paths); + if (turnId === void 0) continue; + const turn = readTurn(paths.runDir, turnId); + if (turn === void 0 || turn.status !== "running" && turn.status !== "starting") continue; + const dead = await killProcessGroup(turn.pgid, grace, signal); + if (!this.generationIsCurrent(generation) || signal.aborted) { + throw new Error("coordinator generation revoked; drain requires current ownership"); + } + if (!dead) failures.push(`${memberId}/${turn.turnId}`); + else { + const landed = turn.sessionId !== null && this.reader.hasUserText(turn.sessionId, turn.promptText); + writeTurn(paths.runDir, { ...turn, status: "exited", exitedAt: iso(this.now()), landed }); + } + } + this.log({ ts: iso(this.now()), kind: "drain-kill", teamId: this.opts.teamId, failures: failures.length }); + if (failures.length > 0) { + throw new Error(`drain left ${failures.length} turn process(es) alive: ${failures.join(", ")}`); + } + } + // ---------------------------------------------------------------- ReconciliationSource / TargetInspector / 呈现 + readProvisioningRecord(memberId) { + const paths = memberPaths(this.teamDir, memberId); + const origin = readOrigin(paths); + if (origin === void 0) return void 0; + let sessionId = origin.sessionId; + if (sessionId === null) { + sessionId = this.resolveSessionId(origin); + if (sessionId !== null && !this.closed) { + writeOrigin(paths, { ...origin, sessionId }); + } + } + if (sessionId === null) { + return { + rootSessionId: origin.teamId, + descriptor: { provider: origin.provider, mode: origin.mode }, + initialUserMessageAccepted: false + }; + } + const session = this.reader.session(sessionId); + if (session === void 0) { + return { + rootSessionId: origin.teamId, + descriptor: { provider: origin.provider, mode: origin.mode }, + initialUserMessageAccepted: false + }; + } + const typeKnown = typeof session.task_type === "string" && session.task_type.length > 0; + const structureOk = !typeKnown ? true : origin.sessionIsolation === "child" ? session.task_type === "selection_side_chat" && (origin.anchorSessionId === void 0 || session.parent_id === origin.anchorSessionId) : session.task_type === "interactive"; + const directoryOk = typeof session.directory !== "string" || session.directory.length === 0 ? true : session.directory === origin.cwd; + const firstText = this.reader.firstRealUserText(sessionId); + const accepted = structureOk && directoryOk && firstText !== void 0 && firstText === origin.firstPromptText; + return { + rootSessionId: origin.teamId, + descriptor: { provider: origin.provider, mode: origin.mode }, + initialUserMessageAccepted: accepted + }; + } + isAlive(memberId) { + const paths = memberPaths(this.teamDir, memberId); + return this.currentRunningTurn(paths) !== null; + } + containsMessage(memberId, messageId) { + if (memberId === this.opts.teamId) { + return receiptMessageIds(memberPaths(this.teamDir, memberId)).has(messageId); + } + const paths = memberPaths(this.teamDir, memberId); + for (const turn of listTurns(paths.runDir)) { + if (!turn.messageIds.includes(messageId)) continue; + if (turn.landed === true) return true; + if (turn.sessionId !== null && this.reader.hasUserText(turn.sessionId, turn.promptText)) return true; + return false; + } + return false; + } + readColdRecord(memberId, messageId) { + const origin = readOrigin(memberPaths(this.teamDir, memberId)); + if (origin === void 0) return void 0; + return { recorded: this.containsMessage(memberId, messageId) }; + } + statusOf(memberId) { + return this.currentRunningTurn(memberPaths(this.teamDir, memberId), true) !== null ? "running" : "inactive"; + } + modelOf(memberId) { + const origin = readOrigin(memberPaths(this.teamDir, memberId)); + if (origin === void 0) return void 0; + let observed; + try { + observed = origin.sessionId !== null ? this.reader.latestModel(origin.sessionId) : void 0; + } catch (err) { + if (!/database (?:table )?is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(errText2(err))) throw err; + this.log({ ts: iso(this.now()), kind: "model-display-unavailable", memberId, error: errText2(err) }); + } + return observed ?? origin.modelSelection?.modelId ?? origin.model; + } + /** Lead 行模型(roster Lead 伪行):Lead 会话最近消息实查 → model_usage 兜底。 */ + leadModelOf() { + try { + return this.reader.latestModel(this.opts.teamId) ?? this.reader.latestModelUsage(this.opts.teamId)?.modelId; + } catch (err) { + if (!/database (?:table )?is locked|SQLITE_BUSY|SQLITE_LOCKED/i.test(errText2(err))) throw err; + this.log({ ts: iso(this.now()), kind: "model-display-unavailable", memberId: this.opts.teamId, error: errText2(err) }); + return void 0; + } + } + /** Lead 当前结构化选择(成员卡/roster 展示用;0.4.0 = 三源判定的可继承选择,可能 undefined)。 */ + leadModelSelectionOf() { + return this.resolveLeadInheritance({ throwOnUnusable: false }); + } + // 0.4.0 注销 setMemberModel:成员模型不存在独立配置通道(唯一路线 = 每轮跟随 Lead)。 + // ---------------------------------------------------------------- hook 回执(Lead 投递 landed 依据) + /** hook 注入成功后落回执(hooks 进程与协调者双写者安全:O_APPEND+fsync)。 */ + recordLeadReceipts(messageIds, channel) { + const paths = memberPaths(this.teamDir, this.opts.teamId); + for (const messageId of messageIds) { + appendReceipt(paths, { messageId, channel, ts: iso(this.now()) }); + } + this.log({ ts: iso(this.now()), kind: "lead-receipt", teamId: this.opts.teamId, channel, messageIds: [...messageIds] }); + } + /** Stop 预算(≤3 次/run;runKey 复位语义见 hooks)。 */ + consumeStopBudget(memberId, runKey) { + const paths = memberPaths(this.teamDir, memberId); + const current = readStopBudget(paths); + const budget = current !== void 0 && current.runKey === runKey ? current : { runKey, blocks: 0 }; + if (budget.blocks >= 3) { + writeStopBudget(paths, budget); + return false; + } + writeStopBudget(paths, { runKey, blocks: budget.blocks + 1 }); + return true; + } + /** + * 空闲 Lead 唤醒(灰度):只在 TEAM_WAKE_LEAD=1、Lead 回合状态为 inactive 且空闲超阈值时 + * 拉起一个“处理收件箱”的 --resume 回合。返回 woke=false 时调用方必须保持 pending。 + */ + wakeLead() { + if (!leadWakeEnabled()) return Promise.resolve({ woke: false, reason: "disabled" }); + return maybeWakeLead({ + teamDir: this.teamDir, + leadSessionId: this.opts.teamId, + cwd: this.cwd, + zcode: this.zcode, + minIdleMs: this.leadWakeMinIdleMs, + now: this.now() + }); + } + close() { + this.detach(); + this.reader.close(); + } + // ---------------------------------------------------------------- 内部 + /** 孵化一轮(turn 记录先落盘 → spawn → 回填 pid/running)。 */ + async launchTurn(args) { + const generation = this.generation; + const turnId = nextTurnId(args.paths.runDir); + const stdoutFile = path17.join(args.paths.runDir, `${turnId}.out`); + const turnCwd = args.cwd ?? this.cwd; + if (this.generationAbort.signal.aborted || args.signal?.aborted) { + throw new ProvisioningPending("\u521B\u5EFA\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4E0D\u4F1A\u542F\u52A8\u65B0 turn"); + } + await this.syncMemberModel( + args.paths, + args.memberId, + args.sessionId, + turnCwd, + args.messageIds, + args.modelJustApplied + ); + if (!this.generationIsCurrent(generation) || args.signal?.aborted) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4E0D\u4F1A\u5199\u5165\u6216\u542F\u52A8\u65B0 turn"); + } + const scriptArgs = [ + ...this.zcode.argvPrefix, + "-p", + args.promptText, + "--json", + "--mode", + "yolo", + "--surface", + "terminal", + "--disallowed-tools", + "Task", + // D6 + "--cwd", + turnCwd, + ...args.resume && args.sessionId !== null ? ["--resume", args.sessionId] : [] + ]; + const turn = { + turnId, + memberId: args.memberId, + kind: args.kind, + sessionId: args.sessionId, + messageIds: args.messageIds, + promptText: args.promptText, + argv: scriptArgs, + pid: null, + pgid: null, + status: "starting", + startedAt: iso(this.now()), + stdoutFile + }; + writeTurn(args.paths.runDir, turn); + setCurrentTurn(args.paths, turnId); + if (this.generationAbort.signal.aborted || args.signal?.aborted) { + throw new ProvisioningPending("\u542F\u52A8\u610F\u56FE\u5DF2\u4FDD\u5B58\u4F46\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4FDD\u6301\u5F85\u6062\u590D\uFF0C\u4E0D\u542F\u52A8"); + } + const env = { + ...process.env, + TEAM_SPAWN_IDENTITY: JSON.stringify({ + teamId: this.opts.teamId, + memberId: args.memberId, + name: args.name + }) + }; + if (this.opts.dbPath !== void 0) env.TEAM_DB_PATH = this.opts.dbPath; + let spawned; + const receiptFile = path17.join(args.paths.runDir, `${turnId}.spawn.json`); + try { + spawned = await spawnDetached({ + command: this.zcode.command, + argv: scriptArgs, + // 真实 env 必须完整传给子进程(API key 等);spec 只短暂存在(helper 读后立即删除,0600)。 + env, + cwd: turnCwd, + stdoutFile, + resultFile: receiptFile + }); + } catch (err) { + if (!this.generationIsCurrent(generation)) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4FDD\u7559\u542F\u52A8\u56DE\u6267\u4F9B\u63A5\u4EFB\u8005\u786E\u8BA4"); + } + const receipt = readSpawnReceipt(receiptFile); + if (receipt?.error !== void 0) { + writeTurn(args.paths.runDir, { ...turn, status: "spawn-error", exitedAt: iso(this.now()), exitCode: null }); + throw new Error(`turn process launch failed: ${receipt.error}`); + } + if (receipt !== void 0 && receipt.pid !== void 0) { + spawned = { pid: receipt.pid, pgid: receipt.pid, stdoutFile, specFile: "", resultFile: receiptFile }; + } else { + throw new ProvisioningPending("\u542F\u52A8\u7ED3\u679C\u5F85\u786E\u8BA4\uFF1B\u4E0D\u4F1A\u91CD\u590D\u542F\u52A8\u9996\u8F6E"); + } + } + if (!this.generationIsCurrent(generation)) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4FDD\u7559\u542F\u52A8\u56DE\u6267\u4F9B\u63A5\u4EFB\u8005\u786E\u8BA4"); + } + const running = { ...turn, pid: spawned.pid, pgid: spawned.pgid, status: "running" }; + writeTurn(args.paths.runDir, running); + if (spawned.pid !== null) this.adoptedPids.add(spawned.pid); + this.log({ + ts: iso(this.now()), + kind: "turn-launch", + teamId: this.opts.teamId, + memberId: args.memberId, + turnId, + kindOfTurn: args.kind, + pid: spawned.pid, + messageIds: args.messageIds, + resume: args.resume, + // 只记 flag 名;prompt/session id/cwd 值不落 provider.jsonl(隐私/体积)。 + argv: [path17.basename(scriptArgs[0] ?? ""), ...scriptArgs.slice(1).map((a) => a.startsWith("--") ? a : "")] + }); + return running; + } + /** 投递必须将无回执的启动视为占用;存活状态与中断仍只认已确认的进程。 */ + currentRunningTurn(paths, includeUnknown = false) { + const turnId = readCurrentTurnId(paths); + if (turnId === void 0) return null; + const turn = readTurn(paths.runDir, turnId); + if (turn === void 0) return null; + if (turn.status !== "running" && turn.status !== "starting") return null; + if (turn.pid === null) { + const receipt = readSpawnReceipt(path17.join(paths.runDir, `${turn.turnId}.spawn.json`)); + if (receipt?.pid === void 0) return includeUnknown ? turn : null; + writeTurn(paths.runDir, { ...turn, pid: receipt.pid, pgid: receipt.pid, status: "running" }); + return { ...turn, pid: receipt.pid, pgid: receipt.pid, status: "running" }; + } + if (!pidAlive(turn.pid)) return null; + return turn; + } + /** 会话 id 认领:session-map(teammate SessionStart hook 经 TEAM_SPAWN_IDENTITY 落的映射)。 */ + claimedSessionId(memberId) { + for (const entry of Object.values(readSessionRegistry(this.opts.dataRoot))) { + if (entry.memberId === memberId && typeof entry.session_id === "string") return entry.session_id; + } + return null; + } + claimedSessionsExcluding(memberId) { + const set = /* @__PURE__ */ new Set(); + for (const entry of Object.values(readSessionRegistry(this.opts.dataRoot))) { + if (entry.memberId !== void 0 && entry.memberId !== memberId && typeof entry.session_id === "string") { + set.add(entry.session_id); + } + } + return set; + } + resolveSessionId(origin) { + const claimed = this.claimedSessionId(origin.memberId); + if (claimed !== null) return claimed; + const createdAtMs = Date.parse(origin.createdAt); + return this.reader.findSessionByFirstPrompt({ + cwd: origin.cwd, + firstPrompt: origin.firstPromptText, + sinceMs: Number.isNaN(createdAtMs) ? 0 : createdAtMs, + excludeSessionIds: this.claimedSessionsExcluding(origin.memberId) + }) ?? null; + } + /** + * Lead 最新**已确认**模型选择(0.4.0 三源判定;成员跟随 Lead 的唯一解析入口)。 + * + * 三源各带时间戳,取最新者(epoch ms): + * 1. real_user 提交快照 —— 宿主在保存用户消息时写入该次提交的 modelSelection, + * 输入框切换在提交瞬间即体现在这里(issue #7 不影响本源:它不刷新 entry,但刷得动消息快照); + * 2. session_entry —— `/model` 命令等会话选模记录(time_updated 识别「提交后的修改」); + * 3. main_turn 实际调用 —— `query_source='main_turn'` 严格过滤,compact/标题/subagent/ + * workflow 等辅助行绝不能当作 Lead 模型(本机实测取值域已核验)。 + * + * 判出后按目录分类:官方套餐(`account:`/`builtin:` 前缀)或目录外(provider/model 不存在 + * 或被禁用)= 不可继承。`throwOnUnusable`(缺省 true): + * - true:spawn/每轮同步入口 —— 不可继承或三源全空 → 抛 ModelInheritanceError(明确报告, + * 绝不静默回退宿主缺省冒充继承成功); + * - false:展示口径(Lead 伪行模型)—— 返回 undefined 交回退链处理。 + * 空目录守卫:目录不可读 = 无法分类 → 不过滤(照旧尝试,宿主 setModel 终审)。 + */ + resolveLeadInheritance(options) { + const throwOnUnusable = options?.throwOnUnusable !== false; + const sources = [ + this.reader.latestSubmissionSelection(this.opts.teamId), + this.reader.latestModelSelectionTimed(this.opts.teamId), + this.reader.latestMainTurnUsage(this.opts.teamId) + ].filter((source) => source !== void 0); + let latest; + if (sources.length > 0) { + const winner = sources.reduce((a, b) => b.at > a.at ? b : a); + latest = winner.selection; + } + if (latest === void 0) { + if (!throwOnUnusable) return void 0; + throw new ModelInheritanceError( + "\u65E0\u6CD5\u786E\u5B9A Lead \u5F53\u524D\u6A21\u578B\uFF08\u4F1A\u8BDD\u5E93\u4E2D\u6CA1\u6709\u63D0\u4EA4\u5FEB\u7167\u3001\u9009\u6A21\u8BB0\u5F55\u6216\u4E3B\u8F6E\u8C03\u7528\uFF09\uFF0C\u6210\u5458\u65E0\u6CD5\u7EE7\u627F\u3002" + ); + } + const model = `${latest.providerId}/${latest.modelId}`; + const isOfficialPlan = latest.providerId.startsWith("account:") || latest.providerId.startsWith("builtin:"); + if (isOfficialPlan) { + if (!throwOnUnusable) return void 0; + throw new ModelInheritanceError( + `Lead \u5F53\u524D\u4F7F\u7528\u5B98\u65B9\u5957\u9910\u6A21\u578B\uFF08${model}\uFF09\uFF0C\u6210\u5458\u65E0\u6CD5\u7EE7\u627F\uFF08CLI \u8FDB\u7A0B\u62FF\u4E0D\u5230\u8BA2\u9605\u5957\u9910\u51ED\u636E\uFF09\u3002\u8BF7\u5728 ZCode \u4E2D\u5207\u6362\u5230\u81EA\u914D\u7684\u7B2C\u4E09\u65B9\u6A21\u578B\u540E\u91CD\u8BD5\uFF1B\u6216\u7531 Lead \u76F4\u63A5\u5B8C\u6210\u8BE5\u5DE5\u4F5C\uFF08\u5355 agent \u515C\u5E95\uFF09\u3002`, + latest + ); + } + const catalog = this.modelCatalog(); + if (catalog.providers.length > 0 && !catalogSupports(catalog, latest)) { + if (!throwOnUnusable) return void 0; + throw new ModelInheritanceError( + `Lead \u6A21\u578B ${model} \u4E0D\u5728\u53EF\u7528\u6A21\u578B\u76EE\u5F55\uFF08Provider \u5DF2\u5220\u9664/\u7981\u7528\uFF0C\u6216\u6A21\u578B\u4E0D\u5B58\u5728\uFF09\uFF0C\u6210\u5458\u65E0\u6CD5\u7EE7\u627F\u3002`, + latest + ); + } + return applyReasoningDefault(catalog, latest); + } + /** + * 每轮执行前同步(0.4.0;0.4.1 修正一致性判断与重试控制): + * Lead 最新已确认选择 ≠ 成员**宿主实际**选择 → setModel 后再启动本轮。 + * - 一致性判断以宿主会话实际选模条目为准;历史调用不能证明下次恢复的选择。 + * origin.modelSelection 只是辅助记录(setModel 成功后 origin 更新前崩溃 → 宿主为准, + * 不能因 origin 相同就放行)。实际状态无法确认(首轮前无任何记录)→ 重新应用 Lead + * 选择(宁多一次 setModel,不带着未确认的模型开跑)。 + * - 确认一致 → 清除旧失败记录(验证成功才清;不因 Lead 改了配置就清)+ 零 RPC。 + * - 应用失败 / Lead 不可继承:写统一失败记录(含类别/尝试次数/退避闸/Lead 指纹/消息 id) + * + 抛 ModelInheritanceError 阻止本轮 —— 绝不带着旧模型或宿主缺省悄悄开跑。 + * - legacy 隔离模式 / 会话未落定(首轮由 createChild 定模):跳过。 + * + * `trigger`:本轮携带的待投递消息 id(失败记录里做「新消息解锁重试」判定;首轮 = [])。 + */ + async syncMemberModel(paths, memberId, sessionId, workspacePath, triggerMessageIds = [], justApplied) { + const generation = this.generation; + if (this.sessionIsolation !== "child" || sessionId === null) return; + let lead; + try { + lead = this.resolveLeadInheritance(); + } catch (err) { + if (err instanceof ModelInheritanceError) { + const selection = err.selection; + const gate2 = this.retryGate(paths, selection, triggerMessageIds); + if (!gate2.allow) { + throw new ModelSyncSuppressedError(err.message, selection); + } + this.recordModelFailure(paths, memberId, err, triggerMessageIds); + } + throw err; + } + if (lead === void 0) return; + const observed = justApplied ?? this.reader.latestModelSelection(sessionId); + if (observed !== void 0 && sameModelSelection(observed, lead)) { + this.clearFailureIfVerified(paths); + const originNow = readOrigin(paths); + if (originNow !== void 0 && (originNow.modelSelection === void 0 || !sameModelSelection(originNow.modelSelection, lead))) { + this.writeCurrentOrigin(paths, { ...originNow, modelSelection: lead, modelSource: "inherited" }); + } + return; + } + const origin = readOrigin(paths); + const gate = this.retryGate(paths, lead, triggerMessageIds); + if (!gate.allow) { + throw new ModelSyncSuppressedError( + `\u6210\u5458 "${memberId}" \u4E0E Lead \u6A21\u578B\uFF08${lead.providerId}/${lead.modelId}\uFF09\u4E0D\u4E00\u81F4\uFF0C\u4E0A\u4E00\u6B21\u540C\u6B65\u5931\u8D25\u5C1A\u672A\u5230\u91CD\u8BD5\u65F6\u673A\uFF1A${gate.reason}`, + lead + ); + } + const result = await this.applySelectionNow(sessionId, workspacePath, lead, memberId); + if (!this.generationIsCurrent(generation)) { + throw new ProvisioningPending("\u534F\u8C03\u8005\u4EE3\u6B21\u5DF2\u64A4\u9500\uFF1B\u4E0D\u4F1A\u5199\u5165\u6A21\u578B\u540C\u6B65\u7ED3\u679C"); + } + if (!result.applied) { + const reason = result.reason ?? "model was rejected by the host"; + const err = new ModelInheritanceError( + `\u6210\u5458 "${memberId}" \u65E0\u6CD5\u540C\u6B65 Lead \u6A21\u578B\uFF08${lead.providerId}/${lead.modelId}\uFF09\uFF1A${reason}`, + lead + ); + this.recordModelFailure(paths, memberId, err, triggerMessageIds, classifyApplyFailure(reason), reason); + throw err; + } + if (origin !== void 0) { + this.writeCurrentOrigin(paths, { ...readOrigin(paths) ?? origin, modelSelection: lead, modelSource: "inherited" }); + } + this.clearFailureIfVerified(paths); + this.log({ + ts: iso(this.now()), + kind: "model-synced", + teamId: this.opts.teamId, + memberId, + providerId: lead.providerId, + modelId: lead.modelId, + reasoningLevel: lead.reasoningLevel ?? null + }); + } + /** + * 自动重试闸(0.4.1):读失败记录,判定本次同步尝试是否放行。 + * - 无记录 / Lead 选择已变(指纹不同)→ 放行(换模 = 重新尝试的显式信号)。 + * - 新消息解锁:trigger 里有记录 messageIds 之外的**新** id → 放行(用户再次明确发送)。 + * - deterministic(含 0.4.0 旧记录无 kind)→ 暂停相同选择的自动重试(拒绝)。 + * - transient → 未到 nextAttemptAt 拒绝;到期且 attempts ≤ 退避序列长度放行; + * 序列耗尽 → 停止自动尝试(拒绝)。 + * `lead` 缺省 = 解析失败(三源全空,无选择指纹)——按记录的 leadSignature 缺省口径同目标。 + */ + retryGate(paths, lead, triggerMessageIds) { + let record2; + try { + record2 = readModelFailed(paths); + } catch { + record2 = void 0; + } + if (record2 === void 0) return { allow: true, reason: "" }; + const signature = lead !== void 0 ? selectionSignature(lead) : void 0; + if (record2.leadSignature !== signature) { + return { allow: true, reason: "" }; + } + const known = new Set(record2.messageIds ?? []); + const hasNewMessage = triggerMessageIds.some((id) => !known.has(id)); + if (hasNewMessage) { + return { allow: true, reason: "" }; + } + const kind = record2.kind ?? "deterministic"; + if (kind === "deterministic") { + return { + allow: false, + reason: `\u76F8\u540C\u9009\u62E9\u7684\u540C\u6B65\u5DF2\u88AB\u786E\u5B9A\u6027\u62D2\u7EDD\uFF08${record2.reason}\uFF09\uFF0C\u7B49\u5F85 Lead \u5207\u6362\u53EF\u7528\u6A21\u578B\u6216\u65B0\u6D88\u606F\u540E\u91CD\u8BD5` + }; + } + const attempts = record2.attempts ?? 1; + const nextAt = record2.nextAttemptAt; + if (nextAt !== void 0 && this.now() < nextAt) { + return { + allow: false, + reason: `\u4E34\u65F6\u6545\u969C\u9000\u907F\u4E2D\uFF08\u7B2C ${attempts} \u6B21\u5C1D\u8BD5\u5DF2\u5931\u8D25\uFF09\uFF0C${Math.ceil((nextAt - this.now()) / 1e3)}s \u540E\u81EA\u52A8\u91CD\u8BD5` + }; + } + if (attempts > this.modelRetryBackoffMs.length) { + return { + allow: false, + reason: `\u4E34\u65F6\u6545\u969C\u5DF2\u8FDE\u7EED\u5931\u8D25 ${attempts - 1} \u6B21\uFF08\u9000\u907F\u5E8F\u5217\u8017\u5C3D\uFF09\uFF0C\u505C\u6B62\u81EA\u52A8\u91CD\u8BD5\uFF1B\u7B49\u5F85 Lead \u5207\u6362\u6A21\u578B\u6216\u65B0\u6D88\u606F` + }; + } + return { allow: true, reason: "" }; + } + /** + * 统一失败记录路径(0.4.1):解析失败(throwOnUnusable 抛出的 ModelInheritanceError)与 + * 宿主应用失败都落到这里——model-failed.json(成员行诊断)+ provider.jsonl + 展示刷新通知。 + * 记录携带重试控制所需全部字段(类别/次数/退避闸/Lead 指纹/触发消息 id);不重建 pending 队列。 + */ + recordModelFailure(paths, memberId, err, triggerMessageIds, kindOverride, reasonOverride) { + const now2 = this.now(); + let previous; + try { + previous = readModelFailed(paths); + } catch { + previous = void 0; + } + const selection = err.selection; + const signature = selection !== void 0 ? selectionSignature(selection) : void 0; + const sameTarget = previous !== void 0 && (previous.leadSignature ?? void 0) === signature; + const kind = kindOverride ?? classifySelectionFailure(err.message); + const attempts = sameTarget && kind === "transient" ? (previous?.attempts ?? 1) + 1 : 1; + const backoff = kind === "transient" ? this.modelRetryBackoffMs[attempts - 1] : void 0; + const messageIds = /* @__PURE__ */ new Set([ + ...sameTarget ? previous?.messageIds ?? [] : [], + ...triggerMessageIds, + ...this.pendingLookup !== null ? this.pendingLookup(memberId).map((item) => item.messageId) : [] + ]); + const record2 = { + ...selection !== void 0 ? { modelSelection: selection } : {}, + reason: compactReason(reasonOverride ?? err.message), + failedAt: iso(now2), + kind, + attempts, + ...backoff !== void 0 ? { nextAttemptAt: now2 + backoff } : {}, + ...signature !== void 0 ? { leadSignature: signature } : {}, + ...messageIds.size > 0 ? { messageIds: [...messageIds] } : {} + }; + writeModelFailed(paths, record2); + this.log({ + ts: iso(now2), + kind: "model-sync-failed", + teamId: this.opts.teamId, + memberId, + failureKind: kind, + attempts, + nextAttemptAt: record2.nextAttemptAt ?? null, + providerId: selection?.providerId ?? null, + modelId: selection?.modelId ?? null, + reason: record2.reason + }); + this.notifyModelFailureChanged(); + } + /** 验证成功才清除(修复4):失败记录存在 → 删除 + 展示刷新通知。调用点均已确认一致/应用成功。 */ + clearFailureIfVerified(paths) { + let existed = false; + try { + existed = readModelFailed(paths) !== void 0; + } catch { + existed = true; + } + clearModelFailed(paths); + if (existed) this.notifyModelFailureChanged(); + } + /** 应用一次模型选择(每轮同步通道:临时实例 resume → setModel;失败返回原因不抛)。 */ + async applySelectionNow(sessionId, workspacePath, selection, memberId) { + if (this.breeder.applyModelSelection === void 0) { + this.log({ ts: iso(this.now()), kind: "model-apply-unsupported", memberId }); + return { applied: false, reason: "breeder does not support model application" }; + } + try { + const result = await this.breeder.applyModelSelection({ sessionId, workspacePath, selection }); + if (!result.applied) { + this.log({ + ts: iso(this.now()), + kind: "model-apply-failed", + teamId: this.opts.teamId, + memberId, + reason: result.reason ?? "unknown" + }); + } + return result; + } catch (err) { + const reason = errText2(err); + this.log({ ts: iso(this.now()), kind: "model-apply-failed", teamId: this.opts.teamId, memberId, reason }); + return { applied: false, reason }; + } + } + /** + * 成员行诊断(GitHub #6 保留面):读 model-failed.json → 一条可读诊断。 + * 无记录/损坏 → [](损坏不阻断 list_agents;失败信息已尽力而为)。 + * 0.4.1:记录可无 modelSelection(三源全空解析不出);transient 附重试进度提示。 + */ + diagnosticsOf(memberId) { + const paths = memberPaths(this.teamDir, memberId); + const origin = readOrigin(paths); + const pending = origin?.creationPending === true && origin.creationDiagnostic !== void 0 ? [origin.creationDiagnostic] : []; + const current = this.currentRunningTurn(paths, true); + if (current !== null && current.pid === null) { + pending.push("\u6210\u5458\u542F\u52A8\u7ED3\u679C\u5F85\u786E\u8BA4\uFF0C\u8FDB\u7A0B\u53EF\u80FD\u4ECD\u5728\u8FD0\u884C\uFF1B\u8BF7\u52FF\u91CD\u590D\u53D1\u9001\u6216\u542F\u52A8\u3002"); + } + let record2; + try { + record2 = readModelFailed(paths); + } catch { + return pending; + } + if (record2 === void 0) return pending; + const reason = typeof record2.reason === "string" ? record2.reason : ""; + const selection = parseModelSelection(record2.modelSelection); + const head = selection !== void 0 ? `\u6210\u5458\u6A21\u578B\u7EE7\u627F\u5931\u8D25\uFF1A${selection.providerId}/${selection.modelId}${reason.length > 0 ? `\uFF08${reason}\uFF09` : ""}` : `\u6210\u5458\u6A21\u578B\u7EE7\u627F\u5931\u8D25\uFF1A${reason}`; + if ((record2.kind ?? "deterministic") === "transient" && (record2.attempts ?? 1) > 1) { + return [`${head}\uFF08\u4E34\u65F6\u6545\u969C\uFF0C\u5DF2\u81EA\u52A8\u91CD\u8BD5 ${record2.attempts - 1} \u6B21\uFF09`, ...pending]; + } + return [head, ...pending]; + } + /** 外层断连只读原请求登记;没有 requestId 关联不能声称已受理。 */ + requestStatus(requestId) { + for (const memberId of listMembers(this.teamDir)) { + const origin = readOrigin(memberPaths(this.teamDir, memberId)); + if (origin?.requestId === requestId) { + return { memberId, accepted: origin.initialUserMessageAccepted }; + } + } + return void 0; + } + /** daemon 侧补写 teammate 映射(hook 未及写时的兜底;不覆盖已有 teammate 映射)。 */ + writeTeammateMapping(sessionId, origin) { + const registry2 = readSessionRegistry(this.opts.dataRoot); + const existing = registry2[sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128)]; + if (existing?.role === "teammate" && existing.memberId !== origin.memberId) return; + upsertSessionEntry(this.opts.dataRoot, sessionId, { + teamId: origin.teamId, + role: "teammate", + name: origin.name, + memberId: origin.memberId + }); + } + /** drain 标记处置(触发点②兜底):keep → 清标记(休眠态,轮次照旧纳管);kill → 补杀。 */ + handleDrainMarker(paths) { + const marker = readJson(paths.drainMarkerFile); + if (marker === void 0) return; + try { + fs18.unlinkSync(paths.drainMarkerFile); + } catch { + } + if (marker.policy === "kill" && marker.turnId !== void 0) { + const turn = readTurn(paths.runDir, marker.turnId); + if (turn !== void 0 && turn.pid !== null && pidAlive(turn.pid)) { + void killProcessGroup(turn.pgid, this.termGraceMs).then((dead) => { + writeTurn(paths.runDir, { ...turn, status: dead ? "exited" : turn.status, exitedAt: iso(this.now()) }); + }).catch(() => void 0); + } + } + } +}; +function listMembers(teamDir) { + const membersDir = path17.join(teamDir, "members"); + let names; + try { + names = fs18.readdirSync(membersDir); + } catch { + return []; + } + return names.filter((n) => !n.startsWith(".")); +} +function safeDir(teamId) { + return teamId.replace(/[^A-Za-z0-9._-]/g, (c) => "~" + c.codePointAt(0).toString(16)); +} +function sha256(text) { + return createHash2("sha256").update(text).digest("hex"); +} +function readSpawnReceipt(file) { + try { + const parsed = JSON.parse(fs18.readFileSync(file, "utf8")); + return { + ...typeof parsed.pid === "number" && Number.isInteger(parsed.pid) && parsed.pid > 0 ? { pid: parsed.pid } : {}, + ...typeof parsed.error === "string" ? { error: parsed.error } : {} + }; + } catch { + return void 0; + } +} +function iso(ms) { + return new Date(ms).toISOString(); +} +function errText2(err) { + return err instanceof Error ? `${err.name}: ${err.message}` : String(err); +} +function compactReason(reason) { + const firstLine = reason.split(/\n/)[0] ?? ""; + const firstSentence = firstLine.split(/(?<=[。!?.!?])\s*/)[0] ?? firstLine; + return truncateReason(firstSentence.trim()); +} +function truncateReason(text) { + if (text.length === 0) return ""; + return text.length > 80 ? `${text.slice(0, 79)}\u2026` : text; +} +function sameModelSelection(a, b) { + return a.providerId === b.providerId && a.modelId === b.modelId && (a.reasoningLevel ?? "") === (b.reasoningLevel ?? ""); +} +function drainPolicyFromEnv() { + return process.env.TEAM_DRAIN_ON_DISPOSE === "kill" ? "kill" : "keep"; +} + +// src/panel/view-service.ts +import fs19 from "node:fs"; +import path18 from "node:path"; + +// src/ui-core/view.ts +var VIEW_STATE_VERSION = 4; +function emptyViewFrame(generatedAt, sessionId) { + return { + type: "view", + stateVersion: VIEW_STATE_VERSION, + team: null, + members: [], + tasks: [], + meta: { generatedAt, revision: 0, ...sessionId !== void 0 ? { sessionId } : {} } + }; +} + +// src/panel/view-service.ts +function snapshotFile(teamDir) { + return path18.join(teamDir, "ui", "view-snapshot.json"); +} +function resolveMemberSession(teamDir, dataRoot, memberId) { + const origin = readOrigin(memberPaths(teamDir, memberId))?.sessionId; + if (origin !== null && origin !== void 0) return origin; + for (const entry of Object.values(readSessionRegistry(dataRoot))) { + if (entry.memberId === memberId && typeof entry.session_id === "string") return entry.session_id; + } + return void 0; +} +function replayFingerprint(teamDir) { + const parts = []; + for (const f of [path18.join(teamDir, "events.jsonl"), path18.join(teamDir, "checkpoint.json")]) { + try { + const st = fs19.statSync(f); + parts.push(`${st.mtimeMs}:${st.size}`); + } catch { + parts.push("missing"); + } + } + return parts.join("|"); +} +function buildStaticFrame(loaded, teamId, generatedAt, sessionId, teamDir, dataRoot) { + const state = loaded.state; + const members = [ + { target: "lead", role: "lead", status: "inactive", diagnostics: [], id: teamId, sessionId: teamId } + ]; + for (const m of state.members) { + const memberSessionId = teamDir !== void 0 && dataRoot !== void 0 ? resolveMemberSession(teamDir, dataRoot, m.id) : void 0; + members.push({ + target: m.name, + role: "teammate", + status: m.phase === "failed" ? "failed" : m.phase === "provisioning" ? "provisioning" : "inactive", + description: m.description, + provider: m.provider, + context: m.context, + diagnostics: m.error !== void 0 ? [m.error] : [], + id: m.id, + ...memberSessionId !== void 0 ? { sessionId: memberSessionId } : {} + }); + } + return { + type: "view", + stateVersion: VIEW_STATE_VERSION, + team: { + teamId, + status: state.failure !== void 0 ? "failure" : "active", + ...state.failure !== void 0 ? { failure: state.failure } : {}, + seq: loaded.seq + }, + members, + tasks: loaded.view.tasks, + meta: { + generatedAt, + revision: loaded.seq, + ...sessionId !== void 0 ? { sessionId } : {} + } + }; +} +var REPLAY_CACHE_MAX = 16; +var PanelViewService = class { + constructor(deps) { + this.deps = deps; + } + replayCache = /* @__PURE__ */ new Map(); + /** + * 推帧判定键:仅覆盖面板**渲染面**(team.status/failure + members + tasks)。 + * 不含 seq/revision——mailbox-only 变化会推进 seq(team/message[/delivered] 事件), + * 但 members/tasks/failure 不变 → 键不变 → 不推帧(F02「mailbox-only 不发帧」口径)。 + */ + contentKey(frame) { + return JSON.stringify({ + // teamId 必须入键:切团队/会话后即便 members/tasks 形状巧合相同,也不得复用上一团队的键。 + teamId: frame.team?.teamId ?? null, + status: frame.team?.status ?? null, + failure: frame.team?.failure ?? null, + members: frame.members, + tasks: frame.tasks + }); + } + /** + * 构建指定会话的团队视图帧。 + * 身份不可解析(无 _meta 且无 hook 映射)→ team:null 空帧(面板呈现加载/不可用, + * 不向订阅者抛错);团队无事件(隐式 Lead 未建团)→ team:null 空帧(不开 host)。 + */ + async buildFrame(meta, sessionIdHint) { + const nowIso = ts(); + let identity; + try { + identity = resolveIdentity({ + dataRoot: this.deps.dataRoot, + meta, + bootTimeMs: this.deps.bootTimeMs + }); + } catch (err) { + this.deps.warn?.(`panel view: identity unresolved (${err instanceof Error ? err.message : String(err)})`); + return emptyViewFrame(nowIso, sessionIdHint); + } + return this.buildFrameForIdentity(identity, nowIso); + } + /** 身份已解析的构帧(team_panel_call refresh 与订阅轮询共用)。 */ + async buildFrameForIdentity(identity, nowIso = ts()) { + const teamId = identity.teamId; + const paths = teamPaths(this.deps.dataRoot, teamId); + if (!fs19.existsSync(paths.eventsFile)) { + const snap = this.readSnapshot(teamId); + if (snap === void 0) { + return { ...emptyViewFrame(nowIso, identity.sessionId), team: null }; + } + return { ...snap, meta: { ...snap.meta, generatedAt: nowIso, sessionId: identity.sessionId } }; + } + const loaded = await this.replay(paths.teamDir, teamId); + const state = loaded.state; + let rows = []; + try { + rows = await this.deps.backend.listAgents(identity); + } catch (err) { + this.deps.warn?.(`panel view: listAgents failed (${err instanceof Error ? err.message : String(err)})`); + } + if (rows.length === 0) { + return buildStaticFrame(loaded, teamId, nowIso, identity.sessionId, paths.teamDir, this.deps.dataRoot); + } + const members = rows.map((row) => { + const snap = row.role === "lead" ? void 0 : state.members.find((m) => m.name === row.target); + const id = row.role === "lead" ? teamId : snap?.id ?? row.target; + const sessionId = row.role === "lead" ? teamId : resolveMemberSession(paths.teamDir, this.deps.dataRoot, id); + return { ...row, id, ...sessionId !== void 0 ? { sessionId } : {} }; + }); + return { + type: "view", + stateVersion: VIEW_STATE_VERSION, + team: { + teamId, + status: state.failure !== void 0 ? "failure" : "active", + ...state.failure !== void 0 ? { failure: state.failure } : {}, + seq: loaded.seq + }, + members, + tasks: loaded.view.tasks, + meta: { + generatedAt: nowIso, + revision: loaded.seq, + sessionId: identity.sessionId + } + }; + } + /** 重放(带指纹缓存;LRU:命中移到队尾,超限淘汰最久未用)。 */ + async replay(teamDir, teamId) { + const fingerprint = replayFingerprint(teamDir); + const cached2 = this.replayCache.get(teamId); + if (cached2 !== void 0 && cached2.fingerprint === fingerprint) { + this.replayCache.delete(teamId); + this.replayCache.set(teamId, cached2); + return cached2.loaded; + } + const loaded = await load(teamDir, teamId); + this.replayCache.delete(teamId); + this.replayCache.set(teamId, { fingerprint, loaded }); + while (this.replayCache.size > REPLAY_CACHE_MAX) { + const oldest = this.replayCache.keys().next().value; + if (oldest === void 0) break; + this.replayCache.delete(oldest); + } + return loaded; + } + /** 帧落盘(teams//ui/view-snapshot.json;tmp+rename 原子替换;失败仅告警)。 */ + writeSnapshot(teamId, frame) { + const file = snapshotFile(teamPaths(this.deps.dataRoot, teamId).teamDir); + try { + fs19.mkdirSync(path18.dirname(file), { recursive: true, mode: 448 }); + const tmp = `${file}.${process.pid}.tmp`; + fs19.writeFileSync(tmp, JSON.stringify(frame), { mode: 384 }); + fs19.renameSync(tmp, file); + } catch (err) { + this.deps.warn?.(`panel view: snapshot write failed (${err instanceof Error ? err.message : String(err)})`); + } + } + /** 读快照(断线重连基线/daemon 冷启动首帧;无/损坏 → undefined)。 */ + readSnapshot(teamId) { + const file = snapshotFile(teamPaths(this.deps.dataRoot, teamId).teamDir); + try { + const parsed = JSON.parse(fs19.readFileSync(file, "utf8")); + return parsed.type === "view" && parsed.stateVersion === VIEW_STATE_VERSION ? parsed : void 0; + } catch { + return void 0; + } + } + /** 重放态直读(detail 合成/team-ctl 共用;无缓存需求场景)。 */ + async loadState(teamId) { + const { teamDir } = teamPaths(this.deps.dataRoot, teamId); + const loaded = await this.replay(teamDir, teamId); + return loaded.state; + } +}; + +// src/panel/detail.ts +var DETAIL_DEFAULT_LIMIT = 100; +var DETAIL_MAX_LIMIT = 200; +var DETAIL_PAGE_BYTES = 256 * 1024; +var TOOL_PAYLOAD_CHARS = 2e3; +var SessionNotSettledError = class extends TeamError { + sessionNotSettled = true; +}; +function resolveMemberSessionId(deps, target, readOriginSession) { + if (target === deps.teamId || target === "lead") { + return { memberId: deps.teamId, sessionId: deps.teamId, name: "lead" }; + } + const member = deps.state.members.find((m) => m.id === target || m.name === target); + if (member === void 0) { + throw new TeamError("TEAM_MEMBER_NOT_FOUND", `active teammate "${target}" not found`); + } + const sessionId = readOriginSession(member.id); + if (sessionId === null || sessionId === void 0) { + throw new SessionNotSettledError( + "TEAM_MEMBER_NOT_FOUND", + `active teammate "${member.name}" not found` + ); + } + return { memberId: member.id, sessionId, name: member.name }; +} +function synthesizeDetailStream(deps, sessionId, memberId) { + const rows = deps.reader.exportDetailParts(sessionId); + const framedQueue = framedFor(deps.state, memberId); + const items = []; + const used = /* @__PURE__ */ new Set(); + for (const row of rows) { + const item = toItem(row); + if (item.role === "user" && item.kind === "text" && item.text !== void 0) { + const idx = framedQueue.findIndex((f, i) => !used.has(i) && textCarriesFrame(item.text, f)); + if (idx >= 0) { + used.add(idx); + item.framed = { messageId: framedQueue[idx].messageId, from: framedQueue[idx].from }; + } + } + items.push(item); + } + return { items }; +} +function framedFor(state, memberId) { + const delivered = new Set(state.delivered); + return state.messages.filter((m) => m.targetId === memberId && delivered.has(m.id)).map((m) => ({ + messageId: m.id, + from: m.senderName, + body: m.content.map((b) => b.type === "text" ? b.text : JSON.stringify(b)).join("\n") + })); +} +function textCarriesFrame(text, framed) { + if (text.includes(`Team message from ${framed.from}:`)) return true; + const anchor = framed.body.slice(0, 64); + return anchor.length >= 8 && text.includes(anchor); +} +function toItem(row) { + const base = { ts: new Date(row.ts).toISOString(), role: row.role }; + if (row.kind === "text") { + return { ...base, kind: "text", text: row.text ?? "" }; + } + const tool = { name: row.toolName ?? "unknown", status: row.toolStatus ?? "unknown" }; + const parts = []; + if (row.toolInput !== void 0) parts.push(`input: ${stringify(row.toolInput)}`); + if (row.toolOutput !== void 0) parts.push(`output: ${stringify(row.toolOutput)}`); + if (parts.length === 0) return { ...base, kind: "toolCall", tool }; + const payload = parts.join("\n"); + return { + ...base, + kind: "toolCall", + tool, + text: payload.length > TOOL_PAYLOAD_CHARS ? payload.slice(0, TOOL_PAYLOAD_CHARS) + "\n\u2026(truncated)" : payload + }; +} +function stringify(v) { + if (typeof v === "string") return v; + try { + return JSON.stringify(v); + } catch { + return String(v); + } +} +function projectSummary(items) { + const out = []; + let round = { tools: [] }; + for (const item of items) { + if (item.role === "user" && item.kind === "text") { + flushRound(out, round); + round = { user: item, tools: [] }; + continue; + } + if (item.kind === "toolCall") { + round.tools.push(item); + continue; + } + if (item.role === "assistant" && item.kind === "text" && (item.text ?? "").trim().length > 0) { + round.conclusion = item; + } + } + flushRound(out, round); + return out; +} +function flushRound(out, round) { + if (round.user !== void 0) out.push(round.user); + if (round.tools.length > 0) out.push(toolGroupItem(round.tools)); + if (round.conclusion !== void 0) out.push(round.conclusion); +} +function toolGroupItem(tools) { + const entries = tools.map((item) => ({ + ts: item.ts, + name: item.tool?.name ?? "unknown", + status: item.tool?.status ?? "unknown", + ...item.text !== void 0 ? { text: item.text } : {} + })); + const last = entries[entries.length - 1]; + return { ts: last.ts, role: "assistant", kind: "toolGroup", count: entries.length, tools: entries }; +} +function pageDetail(items, opts) { + const limit = normalizeLimit(opts.limit); + const total = items.length; + const upper = opts.cursor !== void 0 ? Math.min(opts.cursor - 1, total) : total; + const start = Math.max(0, upper - limit); + let slice = items.slice(start, upper); + let truncated = false; + const bytesOf = (value) => new TextEncoder().encode(JSON.stringify(value)).length; + let bytes = bytesOf(slice); + while (slice.length > 1 && bytes > DETAIL_PAGE_BYTES) { + slice = slice.slice(1); + truncated = true; + bytes = bytesOf(slice); + } + const firstSeq = start + (items.slice(start, upper).length - slice.length) + 1; + const numbered = slice.map((item, i) => ({ seq: firstSeq + i, ...item })); + const page = { items: numbered }; + if (start > 0) page.nextCursor = firstSeq; + return { page, total, truncated }; +} +function normalizeLimit(limit) { + if (limit === void 0) return DETAIL_DEFAULT_LIMIT; + if (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1) { + throw new TeamError("TEAM_INVALID_ARGUMENT", "limit must be a positive safe integer"); + } + return Math.min(limit, DETAIL_MAX_LIMIT); +} +function buildDetail(deps, args, readOriginSession) { + const { memberId, sessionId } = resolveMemberSessionId(deps, args.target, readOriginSession); + const stream = synthesizeDetailStream(deps, sessionId, memberId); + const sourceTotal = stream.items.length; + const projected = projectSummary(stream.items); + const { page, total, truncated } = pageDetail(projected, { + ...args.cursor !== void 0 ? { cursor: args.cursor } : {}, + ...args.limit !== void 0 ? { limit: args.limit } : {} + }); + return { + sessionId, + memberId, + page, + ...truncated ? { truncated: true } : {}, + total, + sourceTotal + }; +} + +// src/panel/panel-call.ts +async function handlePanelCall(deps, args, meta) { + const action = typeof args.action === "string" ? args.action : void 0; + const label = typeof args.label === "string" ? args.label : null; + if (action === void 0 || action === "heartbeat") { + return { kind: "heartbeat", counter: deps.bumpCounter(), ts: now(deps), label }; + } + try { + if (action === "refresh") { + const frame = await deps.view.buildFrame(meta); + return { kind: "view", frame }; + } + if (action === "detail") { + if (typeof args.target !== "string" || args.target.length === 0) { + throw new TeamError("TEAM_INVALID_ARGUMENT", 'param "target" must be a non-empty string'); + } + return { kind: "detail", detail: await buildDetailCall(deps, args, meta) }; + } + throw new TeamError("TEAM_INVALID_ARGUMENT", `unknown panel action "${String(action)}"`); + } catch (err) { + if (err instanceof TeamError) { + const reason = err instanceof SessionNotSettledError ? "session-not-settled" : void 0; + return { kind: "error", code: err.code, message: err.message, ...reason !== void 0 ? { reason } : {} }; + } + const message = err instanceof Error ? err.message : String(err); + deps.warn?.(`panel call failed: ${message}`); + return { kind: "error", code: "", message }; + } +} +async function buildDetailCall(deps, args, meta) { + const identity = resolveIdentity({ + dataRoot: deps.dataRoot, + meta, + bootTimeMs: deps.bootTimeMs + }); + const paths = teamPaths(deps.dataRoot, identity.teamId); + const loaded = await load(paths.teamDir, identity.teamId); + requireMembership(() => { + if (loaded.state.failure !== void 0) throw new Error(loaded.state.failure); + return loaded.state; + }, identity.agentId); + const reader = deps.reader ?? new TranscriptReader(); + const cursor = typeof args.cursor === "number" ? args.cursor : void 0; + const limit = typeof args.limit === "number" ? args.limit : void 0; + return buildDetail( + { teamDir: paths.teamDir, teamId: identity.teamId, state: loaded.state, reader }, + { + target: args.target, + ...cursor !== void 0 ? { cursor } : {}, + ...limit !== void 0 ? { limit } : {} + }, + (memberId) => resolveMemberSession(paths.teamDir, deps.dataRoot, memberId) + ); +} +function now(deps) { + return deps.now !== void 0 ? deps.now() : (/* @__PURE__ */ new Date()).toISOString(); +} + +// src/panel/companion-server.ts +import crypto4 from "node:crypto"; +import fs20 from "node:fs"; +import http from "node:http"; +import path19 from "node:path"; +var COMPANION_REGISTRY_RELPATH = "logs/panel-http.json"; +var SSE_POLL_MS = 500; +function companionRegistryFile(dataRoot) { + const root = path19.resolve(dataRoot); + const file = path19.join(root, COMPANION_REGISTRY_RELPATH); + if (file !== path19.join(root, "logs", "panel-http.json")) { + throw new Error("companion registry path escapes dataRoot"); + } + return file; +} +async function startCompanionServer(deps) { + const token = crypto4.randomBytes(16).toString("hex"); + const registryFile = companionRegistryFile(deps.dataRoot); + const sseClients = /* @__PURE__ */ new Set(); + const backpressured = /* @__PURE__ */ new Set(); + let lastKey = ""; + let lastAnchor = null; + let pushInFlight = null; + let pushDirty = false; + let pollTimer = null; + let closed = false; + const server2 = http.createServer((req, res) => { + void route(req, res); + }); + async function route(req, res) { + const remote = req.socket.remoteAddress; + if (remote !== "127.0.0.1" && remote !== "::1" && remote !== "::ffff:127.0.0.1") { + res.writeHead(403, { "content-type": "text/plain; charset=utf-8" }); + res.end("forbidden"); + return; + } + const url2 = new URL(req.url ?? "/", "http://127.0.0.1"); + const reqToken = url2.searchParams.get("token") ?? headerToken(req); + if (reqToken === null || !timingSafeEqualStr(reqToken, token)) { + res.writeHead(403, { "content-type": "text/plain; charset=utf-8" }); + res.end("forbidden"); + return; + } + if ((url2.pathname === "/" || url2.pathname === "/panel") && (req.method === "GET" || req.method === "HEAD")) { + servePage(res); + return; + } + if (url2.pathname === "/events" && req.method === "GET") { + serveSse(req, res); + return; + } + if (url2.pathname === "/api/call" && req.method === "POST") { + await serveApiCall(req, res); + return; + } + if (url2.pathname === "/healthz" && req.method === "GET") { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: true })); + return; + } + res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }); + res.end("not found"); + } + function headerToken(req) { + const h = req.headers["x-team-token"]; + return typeof h === "string" ? h : null; + } + function servePage(res) { + try { + const html = fs20.readFileSync(deps.pageFile, "utf8"); + res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }); + res.end(html); + } catch (err) { + res.writeHead(500, { "content-type": "text/plain; charset=utf-8" }); + res.end(`companion page unavailable: ${err instanceof Error ? err.message : String(err)}`); + } + } + function serveSse(req, res) { + res.writeHead(200, { + "content-type": "text/event-stream", + "cache-control": "no-store", + connection: "keep-alive" + }); + res.write(`event: hello +data: ${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString() })} + +`); + sseClients.add(res); + res.on("drain", () => backpressured.delete(res)); + req.on("close", () => { + sseClients.delete(res); + backpressured.delete(res); + if (sseClients.size === 0 && pollTimer !== null) { + clearInterval(pollTimer); + pollTimer = null; + } + }); + ensurePolling(); + void pushFrame2(true); + } + function ensurePolling() { + if (pollTimer !== null || closed) return; + pollTimer = setInterval(() => void pushFrame2(false), SSE_POLL_MS); + pollTimer.unref?.(); + } + async function pushFrame2(force) { + if (closed) return; + if (pushInFlight !== null) { + pushDirty = true; + return pushInFlight; + } + pushInFlight = (async () => { + try { + do { + pushDirty = false; + await pushOnce(force); + force = false; + } while (pushDirty && !closed); + } catch (err) { + deps.warn?.(`companion sse push failed: ${err instanceof Error ? err.message : String(err)}`); + } finally { + pushInFlight = null; + } + })(); + return pushInFlight; + } + async function pushOnce(force) { + if (closed) return; + const sessionId = deps.anchoredSession(); + if (sessionId === null) { + lastAnchor = null; + return; + } + if (sseClients.size === 0) return; + const frame = await deps.view.buildFrame({ session_id: sessionId }); + if (deps.anchoredSession() !== sessionId) { + pushDirty = true; + return; + } + const key = deps.view.contentKey(frame); + const anchorChanged = lastAnchor !== sessionId; + if (!force && !anchorChanged && key === lastKey) return; + lastAnchor = sessionId; + lastKey = key; + const payload = `event: view +data: ${JSON.stringify(frame)} + +`; + for (const client of [...sseClients]) { + if (client.writableEnded || backpressured.has(client)) continue; + if (!client.write(payload)) backpressured.add(client); + } + } + async function serveApiCall(req, res) { + const chunks = []; + let total = 0; + for await (const chunk of req) { + total += chunk.length; + if (total > 8192) { + res.writeHead(413, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: false, error: { message: "request body too large" } })); + return; + } + chunks.push(chunk); + } + let args = {}; + try { + const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); + if (typeof parsed === "object" && parsed !== null) args = parsed; + } catch { + res.writeHead(400, { "content-type": "application/json" }); + res.end(JSON.stringify({ ok: false, error: { message: "invalid json body" } })); + return; + } + const sessionId = deps.anchoredSession(); + const meta = sessionId !== null ? { session_id: sessionId } : void 0; + const result = await handlePanelCall( + { ...deps.panelCall, view: deps.view, dataRoot: deps.dataRoot }, + args, + meta + ); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(result)); + } + await new Promise((resolve, reject) => { + server2.once("error", reject); + server2.listen(0, "127.0.0.1", () => { + server2.off("error", reject); + resolve(); + }); + }); + const addr = server2.address(); + const url = `http://127.0.0.1:${addr.port}/panel?token=${token}`; + try { + fs20.mkdirSync(path19.dirname(registryFile), { recursive: true }); + const tmp = `${registryFile}.${process.pid}.tmp`; + fs20.writeFileSync( + tmp, + JSON.stringify({ port: addr.port, token, pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString() }), + { mode: 384 } + ); + fs20.renameSync(tmp, registryFile); + } catch (err) { + deps.warn?.(`companion registry write failed: ${err instanceof Error ? err.message : String(err)}`); + } + return { + url: () => url, + port: () => addr.port, + close: async () => { + if (closed) return; + closed = true; + if (pollTimer !== null) clearInterval(pollTimer); + for (const client of sseClients) client.end(); + sseClients.clear(); + try { + const current = JSON.parse(fs20.readFileSync(registryFile, "utf8")); + if (current.pid === process.pid) fs20.unlinkSync(registryFile); + } catch { + } + await new Promise((resolve) => server2.close(() => resolve())); + } + }; +} +function timingSafeEqualStr(a, b) { + const ba = Buffer.from(a); + const bb = Buffer.from(b); + if (ba.length !== bb.length) return false; + return crypto4.timingSafeEqual(ba, bb); +} + +// src/daemon.ts +var __dirname = path20.dirname(fileURLToPath3(import.meta.url)); +var VIEW_URI = "team://view"; +var PANEL_URI = "ui://agent-team/team-panel.html"; +var NODE_MIN = 22; +var BOOT_TIME_MS = Date.now(); +var nodeMajor = Number(process.versions.node.split(".")[0]); +var nodeWarn = nodeMajor < NODE_MIN ? `agent-team daemon \u9700\u8981 Node >= ${NODE_MIN}\uFF08\u5F53\u524D ${process.versions.node}\uFF09\uFF0C\u9762\u677F\u4E0E\u5DE5\u5177\u53EF\u80FD\u4E0D\u53EF\u7528\u3002\u8BF7\u5B89\u88C5 Node 22+\u3002` : null; +var DATA = dataDir(); +ensurePrivateDir(DATA); +ensurePrivateDir(path20.join(DATA, "logs")); +ensurePrivateDir(path20.join(DATA, "meta")); +ensurePrivateDir(path20.join(DATA, "session-map")); +var staleSpecs = cleanupStaleSpecs(DATA); +var prunedMeta = pruneMetaFiles(DATA); +appendJsonl(path20.join(DATA, "logs", "daemon-lifecycle.jsonl"), { + event: "startup", + ts: ts(), + pid: process.pid, + node: process.versions.node, + execPath: process.execPath, + nodeWarn, + staleSpecsRemoved: staleSpecs, + metaFilesPruned: prunedMeta, + cwd: process.cwd(), + teamEnv: { + TEAM_PLUGIN_DATA: process.env.TEAM_PLUGIN_DATA, + TEAM_PROJECT_DIR: process.env.TEAM_PROJECT_DIR, + TEAM_PLUGIN_ROOT: process.env.TEAM_PLUGIN_ROOT, + ZCODE_SESSION_ID: process.env.ZCODE_SESSION_ID, + // 预期 undefined:env 不注入会话 id(已定案) + TEAM_MAX_MEMBERS: process.env.TEAM_MAX_MEMBERS + } +}); +if (nodeWarn) logErr("daemon", nodeWarn); +var config2 = loadConfig(); +if (!config2.ok) { + logErr("daemon", config2.error); + appendJsonl(path20.join(DATA, "logs", "daemon-lifecycle.jsonl"), { + event: "invalid-config", + ts: ts(), + error: config2.error + }); +} +var interruptEnabled = (process.env.TEAM_INTERRUPT ?? "true") !== "false"; +var leadModeRaw = process.env.TEAM_LEAD_MODE; +var leadMode = validateLeadMode(leadModeRaw); +var leadModeNormalized = normalizeLeadMode(leadModeRaw); +if (leadModeRaw !== void 0 && leadModeNormalized === void 0) { + logErr("daemon", `invalid TEAM_LEAD_MODE ${JSON.stringify(leadModeRaw)} \u2014 falling back to "${leadMode}"`); +} else if (leadModeRaw === "orchestrator" || leadModeRaw === "collaborator") { + logErr( + "daemon", + `legacy TEAM_LEAD_MODE ${JSON.stringify(leadModeRaw)} mapped to "auto" (issue #9) \u2014 use "always" for proactive orchestration` + ); +} +if (config2.ok) { + writeRuntimeConfig({ interrupt: interruptEnabled, leadMode, limits: config2.values }); +} +var sessionIsolation = isolationModeFromEnv(); +var providerLog = (record2) => appendJsonl(path20.join(DATA, "logs", "provider.jsonl"), record2); +var backend = new TeamToolBackend({ + dataRoot: DATA, + limits: config2.ok ? config2.values : DEFAULT_HOST_LIMITS, + interrupt: interruptEnabled, + providerFactory: (teamId) => new ResumePerTurnProvider({ + dataRoot: DATA, + teamId, + cwd: process.env.TEAM_PROJECT_DIR, + sessionIsolation, + log: providerLog + }), + warn: (m) => logErr("backend", m) +}); +appendJsonl(path20.join(DATA, "logs", "provider.jsonl"), { + event: "session-isolation-mode", + mode: sessionIsolation, + ts: ts(), + pid: process.pid +}); +var signalTestMode = fs21.existsSync(path20.join(DATA, "signal-test")); +var signalLog = path20.join(DATA, "logs", "signals.jsonl"); +for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) { + process.on(sig, () => { + appendJsonl(signalLog, { sig, ts: ts(), pid: process.pid, mode: signalTestMode ? "observe" : "graceful" }); + logErr("daemon", `signal ${sig} received`); + if (signalTestMode) return; + const deadline = setTimeout(() => { + appendJsonl(path20.join(DATA, "logs", "daemon-lifecycle.jsonl"), { + event: "dispose-timeout", + ts: ts(), + sig, + pid: process.pid + }); + process.exit(0); + }, 200); + backend.close().then(() => companion !== null ? companion.close() : void 0).then(() => { + appendJsonl(path20.join(DATA, "logs", "daemon-lifecycle.jsonl"), { + event: "dispose-ok", + ts: ts(), + sig, + pid: process.pid + }); + }).catch((err) => { + appendJsonl(path20.join(DATA, "logs", "daemon-lifecycle.jsonl"), { + event: "dispose-failed", + ts: ts(), + sig, + pid: process.pid, + error: err instanceof AggregateError ? `${err.message}: ${err.errors.map((e) => String(e)).join("; ")}` : String(err) + }); + }).finally(() => { + clearTimeout(deadline); + process.exit(0); + }); + }); +} +process.on("exit", (code) => { + appendJsonl(path20.join(DATA, "logs", "daemon-lifecycle.jsonl"), { event: "exit", ts: ts(), code, pid: process.pid }); +}); +var panelView = new PanelViewService({ + dataRoot: DATA, + bootTimeMs: BOOT_TIME_MS, + backend, + warn: (m) => logErr("panel-view", m) +}); +var view = { + counter: 0, + /** resources/subscribe 是连接级布尔订阅(同一客户端重复 subscribe 不叠加计数)。 */ + subscribed: false, + /** 会话锚点代际:切会话即 +1;跨代构帧结果丢弃,避免旧会话帧覆盖新会话。 */ + epoch: 0, + lastFrameTs: null, + /** 最近活跃会话 id(team://view 的团队解析键;callTool _meta 每调更新)。 */ + lastSessionId: null, + lastFrame: null, + lastContentKey: "" +}; +var frameTimer = null; +var pollInFlight = null; +var pollDirty = false; +function setViewSession(sessionId) { + if (view.lastSessionId === sessionId) return; + view.lastSessionId = sessionId; + view.epoch += 1; + view.lastContentKey = ""; + pollDirty = true; +} +async function pollOnce() { + const sessionId = view.lastSessionId; + const epoch = view.epoch; + if (sessionId === null) return; + const frame = await panelView.buildFrame({ session_id: sessionId }); + if (view.epoch !== epoch || view.lastSessionId !== sessionId) { + pollDirty = true; + return; + } + const key = panelView.contentKey(frame); + if (key === view.lastContentKey) return; + view.lastContentKey = key; + view.lastFrame = frame; + view.lastFrameTs = ts(); + if (frame.team !== null) panelView.writeSnapshot(frame.team.teamId, frame); + if (view.subscribed) pushFrame(VIEW_URI); +} +async function pollView() { + if (pollInFlight !== null) { + pollDirty = true; + return pollInFlight; + } + pollInFlight = (async () => { + try { + do { + pollDirty = false; + await pollOnce(); + } while (pollDirty); + } catch (err) { + logErr("panel-view", `poll failed: ${err instanceof Error ? err.message : String(err)}`); + } finally { + pollInFlight = null; + } + })(); + return pollInFlight; +} +var panelCallDeps = { + bootTimeMs: BOOT_TIME_MS, + reader: new TranscriptReader(), + bumpCounter: () => view.counter += 1, + now: ts, + warn: (m) => logErr("panel-call", m) +}; +var companion = null; +if ((process.env.TEAM_COMPANION ?? "") === "1") { + void startCompanionServer({ + dataRoot: DATA, + view: panelView, + panelCall: panelCallDeps, + pageFile: path20.join(__dirname, "ui", "team-companion.html"), + anchoredSession: () => view.lastSessionId, + warn: (m) => logErr("companion", m) + }).then( + (srv) => { + companion = srv; + appendJsonl(path20.join(DATA, "logs", "daemon-lifecycle.jsonl"), { + event: "companion-started", + ts: ts(), + pid: process.pid, + port: srv.port() + }); + logErr("companion", `companion panel listening: ${srv.url()}`); + }, + (err) => logErr("companion", `start failed: ${err instanceof Error ? err.message : String(err)}`) + ); +} +var server = new Server( + { + name: "team-daemon", + version: "0.1.0" + }, + { + capabilities: { + tools: {}, + resources: { subscribe: true, listChanged: false } + } + } +); +var TOOL_PING_DESC = "\u56E2\u961F\u5FC3\u8DF3\u63A2\u9488\uFF08\u8BCA\u65AD\u7528\uFF09\u3002\u8FD4\u56DE daemon \u5B58\u6D3B\u72B6\u6001\u3001\u5F53\u524D\u4F1A\u8BDD\u8EAB\u4EFD\uFF08\u6765\u81EA\u8C03\u7528\u4E0A\u4E0B\u6587\u7684 session_id\uFF09\u4E0E\u914D\u7F6E\u6458\u8981\u3002"; +var TOOLS = [ + { + name: "team_ping", + description: TOOL_PING_DESC, + inputSchema: { + type: "object", + properties: { + echo: { type: "string", description: "\u53EF\u9009\u56DE\u663E\u6587\u672C" } + } + } + }, + { + name: "team_panel_call", + description: "\u9762\u677F\u56DE\u73AF\u5DE5\u5177\uFF08app \u4E13\u7528\uFF09\uFF1A\u9762\u677F\u7ECF callServerTool \u8C03\u7528\u3002label-only = \u5FC3\u8DF3/\u8BA1\u6570\uFF08H12 \u4FDD\u6D3B\u8F7D\u4F53\uFF09\uFF1Baction=refresh = \u5168\u91CF\u89C6\u56FE\u5E27\uFF1Baction=detail + target = \u6210\u5458\u4F1A\u8BDD\u67E5\u770B\u89C6\u56FE\uFF08T5.7\uFF0Ccursor/limit \u5206\u9875\uFF09\u3002detail \u6309\u8F6E\u6458\u8981\uFF08\u4EC5\u7B80\u6D01\u4E00\u79CD\u5F62\u6001\uFF1A\u7528\u6237\u6307\u4EE4 + \u52A8\u4F5C\u7EC4 + \u6BCF\u8F6E\u7ED3\u8BBA\uFF09\u3002", + visibility: ["app"], + inputSchema: { + type: "object", + properties: { + label: { type: "string", description: "\u8C03\u7528\u6765\u6E90\u6807\u6CE8\uFF08\u5982 heartbeat / manual\uFF09" }, + action: { + type: "string", + enum: ["refresh", "detail"], + description: "refresh = \u5168\u91CF\u89C6\u56FE\u5E27\uFF1Bdetail = \u6210\u5458\u4F1A\u8BDD\u67E5\u770B\u89C6\u56FE\uFF08\u9700 target\uFF09" + }, + target: { type: "string", description: "detail \u76EE\u6807\u6210\u5458 id\uFF08\u6216\u6210\u5458\u540D\uFF1Blead \u4EA6\u53EF\uFF09" }, + cursor: { type: "number", description: "detail seq \u6E38\u6807\uFF08\u8FD4\u56DE seq < cursor \u7684\u6700\u8FD1\u4E00\u9875\uFF1B\u7F3A\u7701 = \u672B\u9875/\u6700\u8FD1\u4E0A\u4E0B\u6587\uFF09" }, + limit: { type: "number", description: "detail \u9875\u5927\u5C0F\uFF08\u9ED8\u8BA4 100\uFF0C\u4E0A\u9650 200\uFF09" } + } + } + } +]; +var RESOURCES = [ + { uri: PANEL_URI, name: "agent-team-panel", mimeType: "text/html", description: "\u667A\u80FD\u4F53\u56E2\u961F\u4F1A\u8BDD\u9762\u677F\uFF08\u56E2\u961F\u89C6\u56FE + \u6210\u5458\u4F1A\u8BDD\u4E0B\u94BB\uFF09" }, + { uri: VIEW_URI, name: "agent-team-view", mimeType: "application/json", description: "\u56E2\u961F\u89C6\u56FE\u5E27\uFF08\u8BA2\u9605\u63A8\u9001\u6E90\uFF09" } + // 0.4.0 注销 team://models 资源:成员模型没有配置通道(目录仅 provider 层分类内部使用)。 +]; +server.setRequestHandler(ListToolsRequestSchema, async () => { + appendJsonl(path20.join(DATA, "logs", "requests.jsonl"), { ts: ts(), method: "tools/list" }); + const debugTools = process.env.TEAM_DEBUG_TOOLS === "1"; + const supportTools = debugTools ? TOOLS : TOOLS.filter((t) => t.name !== "team_ping"); + return { tools: [...supportTools, ...listTeamTools({ interrupt: backend.interruptEnabled, leadMode })] }; +}); +server.setRequestHandler(CallToolRequestSchema, async (req, extra) => { + const { name, arguments: args, _meta } = req.params; + const record2 = { + ts: ts(), + tool: sanitizeToolName(name), + params_meta: _meta ?? null, + // H1 证据:每次调用的 _meta 全量 + arguments: redactToolArguments(args ?? null), + sessionIdEnv: process.env.ZCODE_SESSION_ID ?? null + }; + appendJsonl(path20.join(DATA, "logs", "meta-log.jsonl"), record2); + const perCallFile = metaFilePath(DATA, name); + if (perCallFile !== null) { + try { + fs21.writeFileSync(perCallFile, JSON.stringify(record2, null, 2), { mode: 384 }); + } catch (err) { + logErr("daemon", "meta per-call write failed", err instanceof Error ? err.message : String(err)); + } + } + const callSid = _meta?.session_id; + if (typeof callSid === "string" && callSid.length > 0) setViewSession(callSid); + if (!config2.ok) { + return { + isError: true, + content: [{ type: "text", text: config2.error }] + }; + } + if (name === "team_ping") { + view.counter += 1; + const sid = _meta?.session_id; + const body = { + pong: true, + probe: null, + identity: { + session_id: sid ?? null, + // 预期 sess_ 前缀;与所在会话一致(F03 断言) + turn_id: _meta?.turn_id ?? null, + trace_id: _meta?.trace_id ?? null, + workspace_path: _meta?.workspace_path ?? null, + client_mode: _meta?.client_mode ?? null, + delivery_kind: _meta?.delivery_kind ?? null, + meta_keys: _meta ? Object.keys(_meta) : [] + }, + runtime: { node: process.versions.node, pid: process.pid, nodeWarn }, + config: config2.values, + echo: args?.echo ?? null + }; + return { content: [{ type: "text", text: JSON.stringify(body, null, 2) }] }; + } + if (name === "team_panel_call") { + const sid = _meta?.session_id; + if (typeof sid === "string" && sid.length > 0) view.lastSessionId = sid; + const result = await handlePanelCall( + { + view: panelView, + dataRoot: DATA, + ...panelCallDeps + }, + args ?? {}, + _meta + ); + view.lastFrameTs = ts(); + let body; + switch (result.kind) { + case "heartbeat": + body = { ok: true, counter: result.counter, ts: result.ts, label: result.label }; + break; + case "view": + view.lastFrame = result.frame; + view.lastContentKey = panelView.contentKey(result.frame); + if (result.frame.team !== null) { + panelView.writeSnapshot(result.frame.team.teamId, result.frame); + } + body = { ok: true, frame: result.frame }; + break; + case "detail": + body = { ok: true, detail: result.detail }; + break; + // 0.4.0 注销 modelOptions / modelSet 两 case(面板模型通道整体下线)。 + case "error": + body = { + ok: false, + error: { + ...result.code !== "" ? { code: result.code } : {}, + message: result.message, + ...result.reason !== void 0 ? { reason: result.reason } : {} + } + }; + break; + } + return { + // 错误也走正常应答(isError 不置位):面板经 body.error 呈现可读原因并可重试(F14①); + // 通道级失败(daemon 回收)由面板 callServerTool rejection 路径处理。 + content: [{ type: "text", text: JSON.stringify(body) }] + }; + } + if (isTeamTool(name)) { + const meta = _meta; + return callTeamTool( + { + backend, + dataRoot: DATA, + bootTimeMs: BOOT_TIME_MS, + name, + args: args ?? {}, + meta, + leadMode, + signal: extra.signal + }, + // progress 保活:仅 wait_agent + 宿主 progressToken 在场时发(registry 内判定); + // 经 extra.sendNotification(SDK 关联 requestId 的标准路径)。 + // F11 实录:每次发射落 logs/progress.jsonl(报文级证据)。 + { + sendNotification: (notification) => { + appendJsonl(path20.join(DATA, "logs", "progress.jsonl"), { ts: ts(), notification }); + return extra.sendNotification( + notification + ); + } + } + ); + } + throw new Error(`TEAM_UNKNOWN_TOOL: ${name}`); +}); +server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: RESOURCES })); +server.setRequestHandler(ReadResourceRequestSchema, async (req) => { + const { uri } = req.params; + if (uri === PANEL_URI) { + const html = fs21.readFileSync(path20.join(__dirname, "ui", "team-panel.html"), "utf8"); + return { contents: [{ uri, mimeType: "text/html", text: html }] }; + } + if (uri === VIEW_URI) { + let frame = null; + if (view.lastSessionId !== null) { + try { + frame = await panelView.buildFrame({ session_id: view.lastSessionId }); + } catch (err) { + logErr("panel-view", `view read failed: ${err instanceof Error ? err.message : String(err)}`); + } + } + frame ??= view.lastFrame ?? (view.lastSessionId !== null ? panelView.readSnapshot(view.lastSessionId) ?? null : null); + frame ??= emptyViewFrame(ts(), view.lastSessionId ?? void 0); + view.lastFrame = frame; + return { + contents: [ + { uri, mimeType: "application/json", text: JSON.stringify(frame) } + ] + }; + } + throw new Error(`TEAM_UNKNOWN_RESOURCE: ${uri}`); +}); +function pushFrame(uri) { + view.lastFrameTs = ts(); + server.notification({ method: "notifications/resources/updated", params: { uri } }).catch((e) => logErr("daemon", "pushFrame failed", String(e))); +} +server.setRequestHandler(SubscribeRequestSchema, async (req) => { + const { uri } = req.params; + appendJsonl(path20.join(DATA, "logs", "requests.jsonl"), { ts: ts(), method: "resources/subscribe", uri }); + if (uri === VIEW_URI) { + view.subscribed = true; + if (!frameTimer) { + frameTimer = setInterval(() => void pollView(), 500); + frameTimer.unref?.(); + } + await pollView(); + } + return {}; +}); +server.setRequestHandler(UnsubscribeRequestSchema, async (req) => { + const { uri } = req.params; + appendJsonl(path20.join(DATA, "logs", "requests.jsonl"), { ts: ts(), method: "resources/unsubscribe", uri }); + if (uri === VIEW_URI) { + view.subscribed = false; + if (frameTimer) { + clearInterval(frameTimer); + frameTimer = null; + } + } + return {}; +}); +var transport = new StdioServerTransport(); +transport.onclose = () => { + view.subscribed = false; + if (frameTimer) { + clearInterval(frameTimer); + frameTimer = null; + } +}; +await server.connect(transport); +logErr("daemon", `agent-team daemon ready (pid=${process.pid}, node=${process.versions.node}, data=${DATA}, config=${config2.ok ? "ok" : "INVALID"})`); diff --git a/external_plugins/agent-team/runtime/team-hooks.mjs b/external_plugins/agent-team/runtime/team-hooks.mjs new file mode 100644 index 00000000..16fb3fbd --- /dev/null +++ b/external_plugins/agent-team/runtime/team-hooks.mjs @@ -0,0 +1,5959 @@ +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; + +// src/hooks.ts +import fs10 from "node:fs"; +import path11 from "node:path"; + +// src/shared.ts +import fs from "node:fs"; +import path from "node:path"; +import os from "node:os"; + +// src/domain/errors.ts +var TeamError = class extends Error { + code; + constructor(code, message, options) { + super(message, options); + this.name = "TeamError"; + this.code = code; + } + toJSON() { + return serializeTeamError(this); + } +}; +function serializeTeamError(err) { + const out2 = { name: "TeamError", code: err.code, message: err.message }; + const seen = new WeakSet([err]); + const cause = err.cause; + if (cause !== void 0 && cause !== null) out2.cause = serializeCause(cause, seen); + return out2; +} +function serializeCause(cause, seen) { + if (!(cause instanceof Error)) return { message: String(cause) }; + if (seen.has(cause)) return { name: cause.name, message: "[circular cause]" }; + seen.add(cause); + if (cause instanceof TeamError) { + const serialized = { + name: "TeamError", + code: cause.code, + message: cause.message + }; + const inner2 = cause.cause; + if (inner2 !== void 0 && inner2 !== null) serialized.cause = serializeCause(inner2, seen); + return serialized; + } + const plain = { name: cause.name, message: cause.message }; + const inner = cause.cause; + if (inner !== void 0 && inner !== null) plain.cause = serializeCause(inner, seen); + return plain; +} + +// src/domain/config.ts +var DEFAULT_LEAD_MODE = "auto"; +var LEGACY_LEAD_MODE_MAP = { + orchestrator: "auto", + collaborator: "auto" +}; +function normalizeLeadMode(raw2) { + if (typeof raw2 !== "string") return void 0; + if (raw2 === "off" || raw2 === "auto" || raw2 === "always") return raw2; + return LEGACY_LEAD_MODE_MAP[raw2]; +} +function validateLeadMode(raw2) { + return normalizeLeadMode(raw2) ?? DEFAULT_LEAD_MODE; +} + +// src/shared.ts +function dataDir() { + const candidates = [ + process.env.TEAM_PLUGIN_DATA, + process.env.ZCODE_PLUGIN_DATA, + process.env.CLAUDE_PLUGIN_DATA + ]; + for (const c of candidates) if (c && c.trim()) return c; + return path.join(os.homedir(), ".zcode", "agent-team-dev-data"); +} +function ensureDir(p) { + fs.mkdirSync(p, { recursive: true }); + return p; +} +function runtimeConfigPath() { + return path.join(dataDir(), "meta", "runtime-config.json"); +} +function readRuntimeConfig() { + try { + const raw2 = fs.readFileSync(runtimeConfigPath(), "utf8"); + const parsed = JSON.parse(raw2); + if (typeof parsed.interrupt !== "boolean") return void 0; + if (parsed.version !== 2) { + return { ...parsed, version: 2 }; + } + return { ...parsed, leadMode: normalizeLeadMode(parsed.leadMode) }; + } catch { + return void 0; + } +} +function readHostLeadModeOverride(homedir = os.homedir()) { + const file = path.join(homedir, ".zcode", "cli", "config.json"); + let doc; + try { + doc = JSON.parse(fs.readFileSync(file, "utf8")); + } catch { + return void 0; + } + const options = doc?.plugins?.options; + if (options === null || typeof options !== "object") return void 0; + const strings = []; + for (const [key, value] of Object.entries(options)) { + if (!key.startsWith("agent-team")) continue; + if (value !== null && typeof value === "object") { + const mode = value.leadMode; + if (typeof mode === "string" && mode.length > 0) strings.push(mode); + } + } + if (strings.length === 0) return void 0; + const normalized = strings.map((v) => normalizeLeadMode(v)); + if (normalized.some((v) => v === void 0)) return void 0; + const first = normalized[0]; + return normalized.every((v) => v === first) ? first : void 0; +} +function appendJsonl(file, obj) { + fs.appendFileSync(file, JSON.stringify(obj) + "\n", { mode: 384 }); + chmodPrivateOnce(file); +} +function ts() { + return (/* @__PURE__ */ new Date()).toISOString(); +} +var SENSITIVE_ENV_KEY = /(?:^|_)(?:KEY|KEYS|APIKEY|TOKEN|TOKENS|SECRET|SECRETS|PASSWORD|PASSWORDS|PASSWD|PASSPHRASE|AUTH|AUTHORIZATION|COOKIE|CREDENTIAL|CREDENTIALS|PRIVATE|URL|URI|DSN|CONNECTION)(?:$|_)/i; +function isSensitiveEnvKey(key) { + return SENSITIVE_ENV_KEY.test(key); +} +var chmodded = /* @__PURE__ */ new Set(); +function chmodPrivateOnce(file) { + if (chmodded.has(file)) return; + chmodded.add(file); + try { + fs.chmodSync(file, 384); + } catch { + } +} + +// node_modules/zod/v3/external.js +var external_exports = {}; +__export(external_exports, { + BRAND: () => BRAND, + DIRTY: () => DIRTY, + EMPTY_PATH: () => EMPTY_PATH, + INVALID: () => INVALID, + NEVER: () => NEVER, + OK: () => OK, + ParseStatus: () => ParseStatus, + Schema: () => ZodType, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBigInt: () => ZodBigInt, + ZodBoolean: () => ZodBoolean, + ZodBranded: () => ZodBranded, + ZodCatch: () => ZodCatch, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodEffects: () => ZodEffects, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFirstPartyTypeKind: () => ZodFirstPartyTypeKind, + ZodFunction: () => ZodFunction, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNativeEnum: () => ZodNativeEnum, + ZodNever: () => ZodNever, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodParsedType: () => ZodParsedType, + ZodPipeline: () => ZodPipeline, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRecord: () => ZodRecord, + ZodSchema: () => ZodType, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodSymbol: () => ZodSymbol, + ZodTransformer: () => ZodEffects, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + addIssueToContext: () => addIssueToContext, + any: () => anyType, + array: () => arrayType, + bigint: () => bigIntType, + boolean: () => booleanType, + coerce: () => coerce, + custom: () => custom, + date: () => dateType, + datetimeRegex: () => datetimeRegex, + defaultErrorMap: () => en_default, + discriminatedUnion: () => discriminatedUnionType, + effect: () => effectsType, + enum: () => enumType, + function: () => functionType, + getErrorMap: () => getErrorMap, + getParsedType: () => getParsedType, + instanceof: () => instanceOfType, + intersection: () => intersectionType, + isAborted: () => isAborted, + isAsync: () => isAsync, + isDirty: () => isDirty, + isValid: () => isValid, + late: () => late, + lazy: () => lazyType, + literal: () => literalType, + makeIssue: () => makeIssue, + map: () => mapType, + nan: () => nanType, + nativeEnum: () => nativeEnumType, + never: () => neverType, + null: () => nullType, + nullable: () => nullableType, + number: () => numberType, + object: () => objectType, + objectUtil: () => objectUtil, + oboolean: () => oboolean, + onumber: () => onumber, + optional: () => optionalType, + ostring: () => ostring, + pipeline: () => pipelineType, + preprocess: () => preprocessType, + promise: () => promiseType, + quotelessJson: () => quotelessJson, + record: () => recordType, + set: () => setType, + setErrorMap: () => setErrorMap, + strictObject: () => strictObjectType, + string: () => stringType, + symbol: () => symbolType, + transformer: () => effectsType, + tuple: () => tupleType, + undefined: () => undefinedType, + union: () => unionType, + unknown: () => unknownType, + util: () => util, + void: () => voidType +}); + +// node_modules/zod/v3/helpers/util.js +var util; +(function(util2) { + util2.assertEqual = (_) => { + }; + function assertIs(_arg) { + } + util2.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util2.assertNever = assertNever; + util2.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util2.getValidEnumValues = (obj) => { + const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util2.objectValues(filtered); + }; + util2.objectValues = (obj) => { + return util2.objectKeys(obj).map(function(e) { + return obj[e]; + }); + }; + util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util2.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return void 0; + }; + util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); + } + util2.joinValues = joinValues; + util2.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function(objectUtil2) { + objectUtil2.mergeShapes = (first, second) => { + return { + ...first, + ...second + // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +var ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set" +]); +var getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; + +// node_modules/zod/v3/ZodError.js +var ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite" +]); +var quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +var ZodError = class _ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + Object.setPrototypeOf(this, actualProto); + } else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || function(issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof _ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +}; +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; + +// node_modules/zod/v3/locales/en.js +var errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } else { + util.assertNever(issue.validation); + } + } else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "bigint") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; +var en_default = errorMap; + +// node_modules/zod/v3/errors.js +var overrideErrorMap = en_default; +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} + +// node_modules/zod/v3/helpers/parseUtil.js +var makeIssue = (params) => { + const { data, path: path12, errorMaps, issueData } = params; + const fullPath = [...path12, ...issueData.path || []]; + const fullIssue = { + ...issueData, + path: fullPath + }; + if (issueData.message !== void 0) { + return { + ...issueData, + path: fullPath, + message: issueData.message + }; + } + let errorMessage2 = ""; + const maps = errorMaps.filter((m) => !!m).slice().reverse(); + for (const map of maps) { + errorMessage2 = map(fullIssue, { data, defaultError: errorMessage2 }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage2 + }; +}; +var EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, + // contextual error map is first priority + ctx.schemaErrorMap, + // then schema-bound map if available + overrideMap, + // then global override map + overrideMap === en_default ? void 0 : en_default + // then global default map + ].filter((x) => !!x) + }); + ctx.common.issues.push(issue); +} +var ParseStatus = class _ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value + }); + } + return _ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +}; +var INVALID = Object.freeze({ + status: "aborted" +}); +var DIRTY = (value) => ({ status: "dirty", value }); +var OK = (value) => ({ status: "valid", value }); +var isAborted = (x) => x.status === "aborted"; +var isDirty = (x) => x.status === "dirty"; +var isValid = (x) => x.status === "valid"; +var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + +// node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +(function(errorUtil2) { + errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); + +// node_modules/zod/v3/types.js +var ParseInputLazyPath = class { + constructor(parent, value, path12, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path12; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +}; +var handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + } + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap: errorMap2, invalid_type_error, required_error, description } = params; + if (errorMap2 && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap2) + return { errorMap: errorMap2, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +var ZodType = class { + get description() { + return this._def.description; + } + _getType(input2) { + return getParsedType(input2.data); + } + _getOrReturnCtx(input2, ctx) { + return ctx || { + common: input2.parent.common, + data: input2.data, + parsedType: getParsedType(input2.data), + schemaErrorMap: this._def.errorMap, + path: input2.path, + parent: input2.parent + }; + } + _processInputParams(input2) { + return { + status: new ParseStatus(), + ctx: { + common: input2.parent.common, + data: input2.data, + parsedType: getParsedType(input2.data), + schemaErrorMap: this._def.errorMap, + path: input2.path, + parent: input2.parent + } + }; + } + _parseSync(input2) { + const result = this._parse(input2); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input2) { + const result = this._parse(input2); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }; + } catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? { + value: result.value + } : { + issues: ctx.common.issues + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: getParsedType(data) + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } else if (typeof message === "function") { + return message(val); + } else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val) + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement } + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data) + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform } + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def) + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(void 0).success; + } + isNullable() { + return this.safeParse(null).success; + } +}; +var cuidRegex = /^c[^\s-]{8,}$/i; +var cuid2Regex = /^[0-9a-z]+$/; +var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +var uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +var nanoidRegex = /^[a-z0-9_-]{21}$/i; +var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +var durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +var emojiRegex; +var ipv4Regex = /^(?:(?: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])$/; +var ipv4CidrRegex = /^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/; +var ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; +var ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +var dateRegexSource = `((\\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])))`; +var dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "="); + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } catch { + return false; + } +} +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +var ZodString = class _ZodString extends ZodType { + _parse(input2) { + if (this._def.coerce) { + input2.data = String(input2.data); + } + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.string) { + const ctx2 = this._getOrReturnCtx(input2); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx2.parsedType + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input2.data.length < check.value) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input2.data.length > check.value) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "length") { + const tooBig = input2.data.length > check.value; + const tooSmall = input2.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input2, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message + }); + } + status.dirty(); + } + } else if (check.kind === "email") { + if (!emailRegex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "uuid") { + if (!uuidRegex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid") { + if (!cuidRegex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ulid") { + if (!ulidRegex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "url") { + try { + new URL(input2.data); + } catch { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input2.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "trim") { + input2.data = input2.data.trim(); + } else if (check.kind === "includes") { + if (!input2.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "toLowerCase") { + input2.data = input2.data.toLowerCase(); + } else if (check.kind === "toUpperCase") { + input2.data = input2.data.toUpperCase(); + } else if (check.kind === "startsWith") { + if (!input2.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "endsWith") { + if (!input2.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "duration") { + if (!durationRegex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "ip") { + if (!isValidIP(input2.data, check.version)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "jwt") { + if (!isValidJWT(input2.data, check.alg)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "cidr") { + if (!isValidCidr(input2.data, check.version)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64") { + if (!base64Regex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "base64url") { + if (!base64urlRegex.test(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input2.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message) + }); + } + _addCheck(check) { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message) + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message) + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message) + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex, + ...errorUtil.errToObj(message) + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value, + position: options?.position, + ...errorUtil.errToObj(options?.message) + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value, + ...errorUtil.errToObj(message) + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value, + ...errorUtil.errToObj(message) + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message) + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message) + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message) + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }] + }); + } + toLowerCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }] + }); + } + toUpperCase() { + return new _ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }] + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; +} +var ZodNumber = class _ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input2) { + if (this._def.coerce) { + input2.data = Number(input2.data); + } + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.number) { + const ctx2 = this._getOrReturnCtx(input2); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx2.parsedType + }); + return INVALID; + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "min") { + const tooSmall = check.inclusive ? input2.data < check.value : input2.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input2.data > check.value : input2.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (floatSafeRemainder(input2.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "finite") { + if (!Number.isFinite(input2.data)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input2.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodNumber({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message) + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message) + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message) + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value)); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +}; +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodBigInt = class _ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input2) { + if (this._def.coerce) { + try { + input2.data = BigInt(input2.data); + } catch { + return this._getInvalidInput(input2); + } + } + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input2); + } + let ctx = void 0; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input2.data < check.value : input2.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "max") { + const tooBig = check.inclusive ? input2.data > check.value : input2.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message + }); + status.dirty(); + } + } else if (check.kind === "multipleOf") { + if (input2.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { status: status.value, value: input2.data }; + } + _getInvalidInput(input2) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new _ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message) + } + ] + }); + } + _addCheck(check) { + return new _ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message) + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message) + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message) + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +}; +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params) + }); +}; +var ZodBoolean = class extends ZodType { + _parse(input2) { + if (this._def.coerce) { + input2.data = Boolean(input2.data); + } + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input2.data); + } +}; +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params) + }); +}; +var ZodDate = class _ZodDate extends ZodType { + _parse(input2) { + if (this._def.coerce) { + input2.data = new Date(input2.data); + } + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.date) { + const ctx2 = this._getOrReturnCtx(input2); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx2.parsedType + }); + return INVALID; + } + if (Number.isNaN(input2.data.getTime())) { + const ctx2 = this._getOrReturnCtx(input2); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_date + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = void 0; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input2.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date" + }); + status.dirty(); + } + } else if (check.kind === "max") { + if (input2.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input2, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date" + }); + status.dirty(); + } + } else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input2.data.getTime()) + }; + } + _addCheck(check) { + return new _ZodDate({ + ...this._def, + checks: [...this._def.checks, check] + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message) + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message) + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +}; +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params) + }); +}; +var ZodSymbol = class extends ZodType { + _parse(input2) { + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input2.data); + } +}; +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params) + }); +}; +var ZodUndefined = class extends ZodType { + _parse(input2) { + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input2.data); + } +}; +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params) + }); +}; +var ZodNull = class extends ZodType { + _parse(input2) { + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input2.data); + } +}; +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params) + }); +}; +var ZodAny = class extends ZodType { + constructor() { + super(...arguments); + this._any = true; + } + _parse(input2) { + return OK(input2.data); + } +}; +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params) + }); +}; +var ZodUnknown = class extends ZodType { + constructor() { + super(...arguments); + this._unknown = true; + } + _parse(input2) { + return OK(input2.data); + } +}; +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params) + }); +}; +var ZodNever = class extends ZodType { + _parse(input2) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType + }); + return INVALID; + } +}; +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params) + }); +}; +var ZodVoid = class extends ZodType { + _parse(input2) { + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType + }); + return INVALID; + } + return OK(input2.data); + } +}; +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params) + }); +}; +var ZodArray = class _ZodArray extends ZodType { + _parse(input2) { + const { ctx, status } = this._processInputParams(input2); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: tooSmall ? def.exactLength.value : void 0, + maximum: tooBig ? def.exactLength.value : void 0, + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result2) => { + return ParseStatus.mergeArray(status, result2); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new _ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) } + }); + } + max(maxLength, message) { + return new _ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) } + }); + } + length(len, message) { + return new _ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) } + }); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params) + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape + }); + } else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element) + }); + } else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } else { + return schema; + } +} +var ZodObject = class _ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + this.nonstrict = this.passthrough; + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input2) { + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.object) { + const ctx2 = this._getOrReturnCtx(input2); + addIssueToContext(ctx2, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx2.parsedType + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input2); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] } + }); + } + } else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys + }); + status.dirty(); + } + } else if (unknownKeys === "strip") { + } else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } else { + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse( + new ParseInputLazyPath(ctx, value, ctx.path, key) + //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data + }); + } + } + if (ctx.common.async) { + return Promise.resolve().then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet + }); + } + return syncPairs; + }).then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new _ZodObject({ + ...this._def, + unknownKeys: "strict", + ...message !== void 0 ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError + }; + return { + message: defaultError + }; + } + } : {} + }); + } + strip() { + return new _ZodObject({ + ...this._def, + unknownKeys: "strip" + }); + } + passthrough() { + return new _ZodObject({ + ...this._def, + unknownKeys: "passthrough" + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new _ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation + }) + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new _ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape() + }), + typeName: ZodFirstPartyTypeKind.ZodObject + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new _ZodObject({ + ...this._def, + catchall: index + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new _ZodObject({ + ...this._def, + shape: () => shape + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } else { + newShape[key] = fieldSchema.optional(); + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new _ZodObject({ + ...this._def, + shape: () => newShape + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +}; +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params) + }); +}; +var ZodUnion = class extends ZodType { + _parse(input2) { + const { ctx } = this._processInputParams(input2); + const options = this._def.options; + function handleResults(results) { + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }), + ctx: childCtx + }; + })).then(handleResults); + } else { + let dirty = void 0; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + }, + parent: null + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx + }); + if (result.status === "valid") { + return result; + } else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues2) => new ZodError(issues2)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +}; +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params) + }); +}; +var getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } else if (type instanceof ZodLiteral) { + return [type.value]; + } else if (type instanceof ZodEnum) { + return type.options; + } else if (type instanceof ZodNativeEnum) { + return util.objectValues(type.enum); + } else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } else if (type instanceof ZodUndefined) { + return [void 0]; + } else if (type instanceof ZodNull) { + return [null]; + } else if (type instanceof ZodOptional) { + return [void 0, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } else { + return []; + } +}; +var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType { + _parse(input2) { + const { ctx } = this._processInputParams(input2); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator] + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + const optionsMap = /* @__PURE__ */ new Map(); + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new _ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params) + }); + } +}; +function mergeValues(a, b) { + const aType = getParsedType(a); + const bType = getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } else { + return { valid: false }; + } +} +var ZodIntersection = class extends ZodType { + _parse(input2) { + const { status, ctx } = this._processInputParams(input2); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }) + ]).then(([left, right]) => handleParsed(left, right)); + } else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + })); + } + } +}; +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left, + right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params) + }); +}; +var ZodTuple = class _ZodTuple extends ZodType { + _parse(input2) { + const { status, ctx } = this._processInputParams(input2); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array" + }); + status.dirty(); + } + const items = [...ctx.data].map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }).filter((x) => !!x); + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new _ZodTuple({ + ...this._def, + rest + }); + } +}; +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params) + }); +}; +var ZodRecord = class _ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input2) { + const { status, ctx } = this._processInputParams(input2); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new _ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third) + }); + } + return new _ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second) + }); + } +}; +var ZodMap = class extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input2) { + const { status, ctx } = this._processInputParams(input2); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])) + }; + }); + if (ctx.common.async) { + const finalMap = /* @__PURE__ */ new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } else { + const finalMap = /* @__PURE__ */ new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +}; +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params) + }); +}; +var ZodSet = class _ZodSet extends ZodType { + _parse(input2) { + const { status, ctx } = this._processInputParams(input2); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements2) { + const parsedSet = /* @__PURE__ */ new Set(); + for (const element of elements2) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements2) => finalizeSet(elements2)); + } else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new _ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) } + }); + } + max(maxSize, message) { + return new _ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) } + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +}; +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params) + }); +}; +var ZodFunction = class _ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input2) { + const { ctx } = this._processInputParams(input2); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error + } + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error + } + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + const me = this; + return OK(async function(...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } else { + const me = this; + return OK(function(...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new _ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()) + }); + } + returns(returnType) { + return new _ZodFunction({ + ...this._def, + returns: returnType + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new _ZodFunction({ + args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params) + }); + } +}; +var ZodLazy = class extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input2) { + const { ctx } = this._processInputParams(input2); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +}; +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params) + }); +}; +var ZodLiteral = class extends ZodType { + _parse(input2) { + if (input2.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value + }); + return INVALID; + } + return { status: "valid", value: input2.data }; + } + get value() { + return this._def.value; + } +}; +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params) + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params) + }); +} +var ZodEnum = class _ZodEnum extends ZodType { + _parse(input2) { + if (typeof input2.data !== "string") { + const ctx = this._getOrReturnCtx(input2); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input2.data)) { + const ctx = this._getOrReturnCtx(input2); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input2.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return _ZodEnum.create(values, { + ...this._def, + ...newDef + }); + } + exclude(values, newDef = this._def) { + return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef + }); + } +}; +ZodEnum.create = createZodEnum; +var ZodNativeEnum = class extends ZodType { + _parse(input2) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input2); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input2.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues + }); + return INVALID; + } + return OK(input2.data); + } + get enum() { + return this._def.values; + } +}; +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params) + }); +}; +var ZodPromise = class extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input2) { + const { ctx } = this._processInputParams(input2); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap + }); + })); + } +}; +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params) + }); +}; +var ZodEffects = class extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; + } + _parse(input2) { + const { status, ctx } = this._processInputParams(input2); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } else { + status.dirty(); + } + }, + get path() { + return ctx.path; + } + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed2) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed2, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result + })); + }); + } + } + util.assertNever(effect); + } +}; +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params) + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params) + }); +}; +var ZodOptional = class extends ZodType { + _parse(input2) { + const parsedType = this._getType(input2); + if (parsedType === ZodParsedType.undefined) { + return OK(void 0); + } + return this._def.innerType._parse(input2); + } + unwrap() { + return this._def.innerType; + } +}; +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params) + }); +}; +var ZodNullable = class extends ZodType { + _parse(input2) { + const parsedType = this._getType(input2); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input2); + } + unwrap() { + return this._def.innerType; + } +}; +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params) + }); +}; +var ZodDefault = class extends ZodType { + _parse(input2) { + const { ctx } = this._processInputParams(input2); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + removeDefault() { + return this._def.innerType; + } +}; +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params) + }); +}; +var ZodCatch = class extends ZodType { + _parse(input2) { + const { ctx } = this._processInputParams(input2); + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [] + } + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx + } + }); + if (isAsync(result)) { + return result.then((result2) => { + return { + status: "valid", + value: result2.status === "valid" ? result2.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + }); + } else { + return { + status: "valid", + value: result.status === "valid" ? result.value : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data + }) + }; + } + } + removeCatch() { + return this._def.innerType; + } +}; +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params) + }); +}; +var ZodNaN = class extends ZodType { + _parse(input2) { + const parsedType = this._getType(input2); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input2); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType + }); + return INVALID; + } + return { status: "valid", value: input2.data }; + } +}; +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params) + }); +}; +var BRAND = Symbol("zod_brand"); +var ZodBranded = class extends ZodType { + _parse(input2) { + const { ctx } = this._processInputParams(input2); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx + }); + } + unwrap() { + return this._def.type; + } +}; +var ZodPipeline = class _ZodPipeline extends ZodType { + _parse(input2) { + const { status, ctx } = this._processInputParams(input2); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + }; + return handleAsync(); + } else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value + }; + } else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx + }); + } + } + } + static create(a, b) { + return new _ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline + }); + } +}; +var ZodReadonly = class extends ZodType { + _parse(input2) { + const result = this._def.innerType._parse(input2); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +}; +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params) + }); +}; +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom(check, _params = {}, fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r2) => { + if (!r2) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} +var late = { + object: ZodObject.lazycreate +}; +var ZodFirstPartyTypeKind; +(function(ZodFirstPartyTypeKind2) { + ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind2["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +var instanceOfType = (cls, params = { + message: `Input not instance of ${cls.name}` +}) => custom((data) => data instanceof cls, params); +var stringType = ZodString.create; +var numberType = ZodNumber.create; +var nanType = ZodNaN.create; +var bigIntType = ZodBigInt.create; +var booleanType = ZodBoolean.create; +var dateType = ZodDate.create; +var symbolType = ZodSymbol.create; +var undefinedType = ZodUndefined.create; +var nullType = ZodNull.create; +var anyType = ZodAny.create; +var unknownType = ZodUnknown.create; +var neverType = ZodNever.create; +var voidType = ZodVoid.create; +var arrayType = ZodArray.create; +var objectType = ZodObject.create; +var strictObjectType = ZodObject.strictCreate; +var unionType = ZodUnion.create; +var discriminatedUnionType = ZodDiscriminatedUnion.create; +var intersectionType = ZodIntersection.create; +var tupleType = ZodTuple.create; +var recordType = ZodRecord.create; +var mapType = ZodMap.create; +var setType = ZodSet.create; +var functionType = ZodFunction.create; +var lazyType = ZodLazy.create; +var literalType = ZodLiteral.create; +var enumType = ZodEnum.create; +var nativeEnumType = ZodNativeEnum.create; +var promiseType = ZodPromise.create; +var effectsType = ZodEffects.create; +var optionalType = ZodOptional.create; +var nullableType = ZodNullable.create; +var preprocessType = ZodEffects.createWithPreprocess; +var pipelineType = ZodPipeline.create; +var ostring = () => stringType().optional(); +var onumber = () => numberType().optional(); +var oboolean = () => booleanType().optional(); +var coerce = { + string: (arg) => ZodString.create({ ...arg, coerce: true }), + number: (arg) => ZodNumber.create({ ...arg, coerce: true }), + boolean: (arg) => ZodBoolean.create({ + ...arg, + coerce: true + }), + bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), + date: (arg) => ZodDate.create({ ...arg, coerce: true }) +}; +var NEVER = INVALID; + +// src/domain/events.ts +var IMAGE_MEDIA_TYPES = ["png", "jpeg", "webp", "gif"]; +function validateContentBlock(block) { + if (typeof block !== "object" || block === null || Array.isArray(block)) { + throw new Error("content block must be a JSON object"); + } + const b = block; + switch (b.type) { + case "text": + case "reasoning": + if (typeof b.text !== "string") throw new Error(`${String(b.type)} block requires string text`); + return block; + case "image": { + const a = b.attachment; + if (typeof a !== "object" || a === null || Array.isArray(a)) { + throw new Error("image block requires object attachment"); + } + const att = a; + if (typeof att.attachmentId !== "string") throw new Error("image attachment requires string attachmentId"); + if (typeof att.mediaType !== "string" || !IMAGE_MEDIA_TYPES.includes(att.mediaType)) { + throw new Error(`image attachment mediaType must be one of ${IMAGE_MEDIA_TYPES.join("/")}`); + } + if (typeof att.bytes !== "number") throw new Error("image attachment requires number bytes"); + if (typeof att.width !== "number") throw new Error("image attachment requires number width"); + if (typeof att.height !== "number") throw new Error("image attachment requires number height"); + if (att.name !== void 0 && typeof att.name !== "string") { + throw new Error("image attachment name must be a string when present"); + } + return block; + } + case "tool-call": { + if (typeof b.id !== "string") throw new Error("tool-call block requires string id"); + if (typeof b.name !== "string") throw new Error("tool-call block requires string name"); + if (!("arguments" in b)) throw new Error("tool-call block requires arguments"); + return block; + } + case "tool-result": + throw new Error("retired tool-result wrapper is not accepted as Team message content"); + default: + return block; + } +} +var contentBlocksSchema = external_exports.array(external_exports.unknown()).superRefine((blocks, ctx) => { + for (let i = 0; i < blocks.length; i++) { + try { + validateContentBlock(blocks[i]); + } catch (err) { + ctx.addIssue({ + code: external_exports.ZodIssueCode.custom, + path: [i], + message: err instanceof Error ? err.message : String(err) + }); + } + } +}); +var TASK_ID_PATTERN = /^task-(\d+)$/; +function isLooseIdValid(id) { + if (id.length === 0) return false; + const m = id.match(TASK_ID_PATTERN); + if (m && !Number.isSafeInteger(Number(m[1]))) return false; + return true; +} +function taskNumberFromId(id) { + const m = id.match(TASK_ID_PATTERN); + return m ? Number(m[1]) : void 0; +} +var looseIdSchema = external_exports.string().refine(isLooseIdValid, { message: "invalid loose id" }); +var memberSnapshotSchema = external_exports.strictObject({ + id: external_exports.string(), + name: external_exports.string(), + description: external_exports.string(), + provider: external_exports.string(), + context: external_exports.enum(["fresh", "fork"]), + phase: external_exports.enum(["provisioning", "active", "failed"]), + error: external_exports.string().optional() +}); +var taskSnapshotSchema = external_exports.strictObject({ + id: looseIdSchema, + revision: external_exports.number().refine((n) => Number.isSafeInteger(n) && n >= 1, { + message: "revision must be a positive safe integer" + }), + subject: external_exports.string(), + description: external_exports.string(), + status: external_exports.enum(["pending", "in_progress", "completed", "deleted"]), + ownerId: external_exports.string().optional(), + blockedBy: external_exports.array(external_exports.string()), + writeScopes: external_exports.array(external_exports.string()) +}); +var messageSnapshotSchema = external_exports.strictObject({ + id: looseIdSchema, + senderId: external_exports.string(), + senderName: external_exports.string(), + targetId: external_exports.string(), + content: contentBlocksSchema +}); +var TEAM_EVENT_VERSION = 2; +var TEAM_EVENT_TYPES = [ + "team/member", + "team/task", + "team/message/queued", + "team/message/delivered" +]; +var memberEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/member"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + member: memberSnapshotSchema +}); +var taskEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/task"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + task: taskSnapshotSchema +}); +var messageQueuedEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/message/queued"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + message: messageSnapshotSchema +}); +var messageDeliveredEventSchema = external_exports.strictObject({ + type: external_exports.literal("team/message/delivered"), + version: external_exports.literal(TEAM_EVENT_VERSION), + teamId: external_exports.string(), + messageId: external_exports.string(), + targetId: external_exports.string() +}); +var TEAM_EVENT_SCHEMAS = { + "team/member": memberEventSchema, + "team/task": taskEventSchema, + "team/message/queued": messageQueuedEventSchema, + "team/message/delivered": messageDeliveredEventSchema +}; +var LEGACY_EVENT_TYPE_ALIASES = { + "team/message": "team/message/queued" +}; +function selectTeamEvent(raw2, teamId) { + if (typeof raw2 !== "object" || raw2 === null || Array.isArray(raw2)) return { kind: "ignored" }; + const candidate = raw2; + const rawType = candidate.type; + if (typeof rawType !== "string") return { kind: "ignored" }; + const eventType = TEAM_EVENT_TYPES.includes(rawType) ? rawType : LEGACY_EVENT_TYPE_ALIASES[rawType]; + if (eventType === void 0) return { kind: "ignored" }; + if (typeof candidate.teamId !== "string" || candidate.teamId !== teamId) { + return { kind: "ignored" }; + } + if (candidate.version !== TEAM_EVENT_VERSION) { + return { kind: "unsupported-version", version: candidate.version }; + } + const normalized = rawType === eventType ? raw2 : { ...candidate, type: eventType }; + const parsed = TEAM_EVENT_SCHEMAS[eventType].safeParse(normalized); + if (!parsed.success) return { kind: "invalid-payload", type: eventType }; + return { kind: "event", event: parsed.data }; +} +var deliveredIdsSchema = external_exports.preprocess((value) => { + if (!Array.isArray(value)) return value; + return value.map((item) => { + if (typeof item === "string") return item; + if (typeof item === "object" && item !== null && typeof item.messageId === "string") { + return item.messageId; + } + return item; + }); +}, external_exports.array(external_exports.string())); +var teamStateSchema = external_exports.strictObject({ + id: external_exports.string(), + members: external_exports.array(memberSnapshotSchema), + tasks: external_exports.array(taskSnapshotSchema), + messages: external_exports.array(messageSnapshotSchema), + delivered: deliveredIdsSchema, + nextTaskNumber: external_exports.number().refine((n) => Number.isSafeInteger(n) && n >= 1, { + message: "nextTaskNumber must be a positive safe integer" + }), + failure: external_exports.string().optional() +}); + +// src/domain/task-graph.ts +function validateTaskGraph(tasks) { + const byId = new Map(tasks.map((t) => [t.id, t])); + const live = tasks.filter((t) => t.status !== "deleted"); + for (const task of live) { + for (const bid of task.blockedBy) { + if (bid === task.id) { + throw new Error(`team task "${task.id}" cannot block itself`); + } + } + } + for (const task of live) { + const seen = /* @__PURE__ */ new Set(); + for (const bid of task.blockedBy) { + if (seen.has(bid)) { + throw new Error(`team task "${task.id}" repeats blocker "${bid}"`); + } + seen.add(bid); + } + } + for (const task of live) { + for (const bid of task.blockedBy) { + const blocker = byId.get(bid); + if (blocker === void 0 || blocker.status === "deleted") { + throw new Error(`blocker task "${bid}" for "${task.id}" is missing or deleted`); + } + } + } + detectCycle(live, byId); +} +function detectCycle(live, byId) { + const WHITE = 0; + const GRAY = 1; + const BLACK = 2; + const color = /* @__PURE__ */ new Map(); + const visit = (task) => { + color.set(task.id, GRAY); + for (const bid of task.blockedBy) { + const blocker = byId.get(bid); + if (blocker === void 0 || blocker.status === "deleted") continue; + const c = color.get(bid) ?? WHITE; + if (c === GRAY) { + throw new Error(`task dependency cycle includes "${bid}"`); + } + if (c === WHITE) visit(blocker); + } + color.set(task.id, BLACK); + }; + for (const task of live) { + if ((color.get(task.id) ?? WHITE) === WHITE) visit(task); + } +} + +// src/domain/task-view.ts +function taskReady(state, task) { + return task.blockedBy.every((bid) => { + const blocker = state.tasks.find((t) => t.id === bid); + return blocker !== void 0 && blocker.status === "completed"; + }); +} +function projectTaskView(state, task) { + const view = { + id: task.id, + revision: task.revision, + subject: task.subject, + description: task.description, + status: task.status, + blockedBy: [...task.blockedBy], + writeScopes: [...task.writeScopes], + ready: task.status === "pending" && taskReady(state, task), + writeScopeWarnings: writeScopeWarnings(state, task) + }; + if (task.ownerId !== void 0) { + const ownerName = task.ownerId === state.id ? "lead" : state.members.find((m) => m.id === task.ownerId)?.name; + if (ownerName !== void 0) view.ownerName = ownerName; + } + return view; +} +function writeScopeWarnings(state, task) { + if (task.status !== "in_progress") return []; + const warnings = /* @__PURE__ */ new Set(); + for (const other of state.tasks) { + if (other.id === task.id || other.status !== "in_progress") continue; + if (scopesOverlap(task.writeScopes, other.writeScopes)) { + warnings.add(`write scopes overlap with ${other.id}`); + } + } + return [...warnings]; +} +function scopesOverlap(left, right) { + for (const l of left) { + for (const r of right) { + if (l === r || l.startsWith(r + "/") || r.startsWith(l + "/")) return true; + } + } + return false; +} + +// src/domain/projection.ts +var TEAM_PROJECTION_STATE_VERSION = 4; +function emptyTeamState(rootId) { + return { + id: rootId, + members: [], + tasks: [], + messages: [], + delivered: [], + nextTaskNumber: 1 + }; +} +function failed(state, failure) { + return { ...state, failure }; +} +function applyProjectionEvent(state, raw2) { + if (state.failure !== void 0) return state; + const selected = selectTeamEvent(raw2, state.id); + switch (selected.kind) { + case "ignored": + return state; + case "unsupported-version": + return failed(state, `unsupported Agent Teams event version ${String(selected.version)}`); + case "invalid-payload": + return failed(state, `persisted Agent Teams ${selected.type} payload is invalid`); + case "event": + return applyCurrentTeamEvent(state, selected.event); + } +} +function applyCurrentTeamEvent(state, event2) { + if (state.failure !== void 0) return state; + switch (event2.type) { + case "team/member": + return applyMember(state, event2.member); + case "team/task": + return applyTask(state, event2.task); + case "team/message/queued": + return applyMessageQueued(state, event2.message); + case "team/message/delivered": + return applyMessageDelivered(state, event2.messageId, event2.targetId); + } +} +function applyMember(state, member) { + const prior = state.members.find((m) => m.id === member.id); + if (prior === void 0) { + if (member.phase !== "provisioning") { + return failed(state, `teammate "${member.name}" must begin provisioning`); + } + if (state.members.some((m) => m.name === member.name)) { + return failed(state, `teammate name "${member.name}" is reused by another member`); + } + return { ...state, members: [...state.members, member] }; + } + if (prior.name !== member.name || prior.provider !== member.provider || prior.context !== member.context) { + return failed(state, `teammate "${prior.id}" changed immutable identity fields`); + } + if (prior.phase !== "provisioning" || member.phase !== "active" && member.phase !== "failed") { + return failed( + state, + `teammate "${member.name}" has an invalid ${prior.phase} -> ${member.phase} transition` + ); + } + return { ...state, members: state.members.map((m) => m.id === member.id ? member : m) }; +} +function applyTask(state, task) { + const prior = state.tasks.find((t) => t.id === task.id); + const expectedRevision = prior === void 0 ? 1 : prior.revision + 1; + if (task.revision !== expectedRevision) { + return failed( + state, + prior === void 0 ? `team task "${task.id}" must begin at revision 1` : `team task "${task.id}" revision is not contiguous` + ); + } + const tasks = prior === void 0 ? [...state.tasks, task] : state.tasks.map((t) => t.id === task.id ? task : t); + try { + validateTaskGraph(tasks); + } catch (err) { + return failed(state, err instanceof Error ? err.message : String(err)); + } + let nextTaskNumber = state.nextTaskNumber; + const n = taskNumberFromId(task.id); + if (n !== void 0) { + nextTaskNumber = Math.max(state.nextTaskNumber, Math.min(n + 1, Number.MAX_SAFE_INTEGER)); + } + return { ...state, tasks, nextTaskNumber }; +} +function applyMessageQueued(state, message) { + if (state.messages.some((m) => m.id === message.id)) { + return failed(state, `team message "${message.id}" was queued twice`); + } + return { ...state, messages: [...state.messages, message] }; +} +function applyMessageDelivered(state, messageId, targetId) { + const queued = state.messages.find((m) => m.id === messageId); + if (queued === void 0) { + return failed(state, `team message "${messageId}" was delivered before queueing`); + } + if (queued.targetId !== targetId) { + return failed(state, `team message "${messageId}" target changed`); + } + if (state.delivered.includes(messageId)) { + return failed(state, `team message "${messageId}" was delivered twice`); + } + return { ...state, delivered: [...state.delivered, messageId] }; +} +var viewCache = /* @__PURE__ */ new WeakMap(); +function teamProjectionView(state) { + let byTasks = viewCache.get(state.members); + if (byTasks === void 0) { + byTasks = /* @__PURE__ */ new WeakMap(); + viewCache.set(state.members, byTasks); + } + let entry = byTasks.get(state.tasks); + if (entry === void 0) { + const members = [ + { id: state.id, name: "lead", role: "lead", phase: "active" }, + ...state.members.map((m) => ({ id: m.id, name: m.name, role: "teammate", phase: m.phase, ...m.error !== void 0 ? { error: m.error } : {} })) + ]; + const tasks = state.tasks.filter((t) => t.status !== "deleted").map((t) => projectTaskView(state, t)); + entry = { healthy: { members, tasks } }; + byTasks.set(state.tasks, entry); + } + if (state.failure === void 0) return entry.healthy; + if (entry.failed === void 0) { + entry.failed = { ...entry.healthy, failure: state.failure }; + } + return entry.failed; +} + +// src/mcp/policy.ts +function teamPolicy(interrupt) { + return `Agent Teams is available in this session + +The Team Lead and all teammates share the same working directory and filesystem. Edits are immediately visible to every member. Split write work into disjoint scopes, record expected write scopes on shared tasks, and use task dependencies when work must be ordered. Write-scope overlap is advisory, not a lock. + +Prefer read/edit/write for file changes. If a file operation reports that the file changed since you last read it, read the current file again, rebase your intended change onto the new content, and retry. Bash, formatters, code generators, and scripts are not fully protected by the filesystem version guard; coordinate them explicitly and have the Lead review the final diff and run tests. + +Use the target returned by spawn_teammate or list_agents for send_message${interrupt ? " and interrupt_agent" : ""}, or as owner when assigning or filtering shared tasks. send_message queues delivery to a running teammate's next turn boundary and starts or resumes an inactive teammate. The Lead receives queued messages through wait_agent during its current turn, with session hooks as a fallback. inactive means no turn is executing; it does not describe task completion, success, failure, or waiting for other agents. provisioning means member creation is in progress; failed means member creation failed. A peer message starts with its sender name. A successful send does not mean the recipient has processed it. Each delegated unit needs a shared task with acceptance criteria. Create it before dispatching the work; the teammate must list/get it, claim with the current revision, perform the work, then complete and report to the Lead. An initial prompt or an output file is not a task-board record. Task readiness never starts an owner. Use wait_agent to receive pending Lead inbox messages before sending follow-ups, even when teammates are inactive. With no pending messages, it waits for new changes and returns noProgress immediately when no other member can produce a change; it never wakes a member. Consume returned messages, then recheck shared tasks before deciding whether more work or another message is needed. Re-list after wakeup or timeout. The Lead must wait for required teammates before giving the final answer.`; +} +var POLICY_TEXT = teamPolicy(true); +var HOOK_POLICY_PREFIX = "[agent-team]"; +var IDENTITY_LEAD_TEXT = `You are the Team Lead named "lead". +Use list_agents({}) to find your teammates and their names. +To message another teammate, use send_message({ target: "", message: "..." }).`; +function identityTeammateText(name) { + return `You are teammate "${name}". +Your Team Lead is named "lead". +To message your Team Lead, use send_message({ target: "lead", message: "..." }). +Use list_agents({}) to find your teammates and their names. +To message another teammate, use send_message({ target: "", message: "..." }).`; +} +var POLICY_PROBE_MARKER = "quartz-ember-73"; +var ORCHESTRATOR_SECTION_TEXT = "Lead operating mode (orchestrator): Decompose any non-trivial multi-step request into disjoint work packages before doing hands-on work. Do not edit files or implement directly except trivial one-line fixes or when no eligible member exists \u2014 delegate by creating teammates that cover the roles the goal requires. You decide the team composition and spawn it without being asked; consult the user only when the choice materially changes cost or scope. Turn every delegated unit into a shared task whose description states concrete acceptance criteria, assign an owner, record expected write scopes, and set dependencies when ordering matters. Require each owner to self-check and report changed files and test results before completing. When a task reaches completed, verify it independently: review the final diff and run the relevant tests yourself; if it fails, reopen the task with concrete findings; if it passes, append your acceptance verdict to the task description \u2014 a task is done when completed plus your recorded acceptance. Reuse idle teammates before spawning new ones and keep one member per role, within the member limit. You still wait for required teammates and synthesize their results for the final answer."; +var ON_DEMAND_SECTION_TEXT = "Lead operating mode (on-demand): Judge each request by delegation value before using the team. Handle work directly yourself \u2014 with a one-line reason, no forced tasks \u2014 for questions and explanations, small changes confined to a single file, read-only research summaries, or when every teammate is busy and the request is unrelated to existing work. Use the team workflow when work clearly benefits from multiple roles in parallel, when write scopes must be split across members, when a long task deserves its own context, or when the user explicitly names members. When you delegate, turn each delegated unit into a shared task whose description states concrete acceptance criteria, assign an owner, record expected write scopes, and set dependencies when ordering matters. Require each owner to self-check and report changed files and test results before completing. When a task reaches completed, verify it independently: review the final diff and run the relevant tests yourself; if it fails, reopen the task with concrete findings; if it passes, append your acceptance verdict to the task description \u2014 a task is done when completed plus your recorded acceptance. Reuse idle teammates before spawning new ones and keep one member per role, within the member limit. Wait for required teammates and synthesize their results for the final answer."; +var FIRST_SPAWN_NOTE = `[agent-team] Team mode is now active: this is the first teammate of this session. +${ON_DEMAND_SECTION_TEXT}`; +var DEGRADED_SOLO_NOTE = "[agent-team] Heads-up (informational, not a restriction): in this session the Lead's model is an official plan model whose credentials teammate processes cannot inherit, so a spawn_teammate call made right now would fail with an inheritance error. Doing the work directly is the reliable path while that remains true. This is a statement of the current state, not a standing rule: the moment the Lead's model is a self-configured third-party provider, spawn_teammate works normally \u2014 just call it as usual, no extra confirmation needed. Ask the user to switch the Lead model if teammates are wanted."; +var SOLO_RETRACT_NOTE = "[agent-team] Update \u2014 the earlier unavailability notice no longer applies. The Lead's model is now a self-configured third-party provider, so teammate processes can inherit it and spawn_teammate works normally. Treat that earlier notice as superseded and expired; any instruction in it to avoid spawn_teammate is void. Call spawn_teammate as usual whenever delegation adds value \u2014 no re-confirmation needed. Also tell the user in one short line that teammates are available again (they cannot see this notice, and 2026-11-02 feedback showed the recovery was invisible to them)."; +function buildSessionStartContext(identityText, interrupt = true, modeSection) { + const policy = teamPolicy(interrupt); + const section = modeSection !== void 0 ? ` +${HOOK_POLICY_PREFIX} ${modeSection}` : ""; + const probe = process.env.TEAM_POLICY_PROBE === "1" ? ` +${HOOK_POLICY_PREFIX} \u7B56\u7565\u6CE8\u5165\u9A8C\u8BC1\u6807\u8BB0\uFF1A${POLICY_PROBE_MARKER}` : ""; + return `${HOOK_POLICY_PREFIX} ${policy} +${HOOK_POLICY_PREFIX} ${identityText}${section}${probe}`; +} +var SESSION_START_CONTEXT = buildSessionStartContext(IDENTITY_LEAD_TEXT, true); + +// src/mcp/identity.ts +import fs2 from "node:fs"; +import path2 from "node:path"; +function sessionMapPath(dataRoot) { + return path2.join(dataRoot, "session-map.json"); +} +function safeSessionKey(sessionId) { + return sessionId.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128); +} +function registryLockPath(dataRoot) { + return `${sessionMapPath(dataRoot)}.lock`; +} +function withRegistryLock(dataRoot, fn) { + const lock = registryLockPath(dataRoot); + const started = Date.now(); + let fd = null; + while (Date.now() - started < 2e3) { + try { + fd = fs2.openSync(lock, "wx", 384); + break; + } catch { + try { + const stat = fs2.statSync(lock); + if (Date.now() - stat.mtimeMs > 5e3) fs2.unlinkSync(lock); + } catch { + } + const until = Date.now() + 20; + while (Date.now() < until) { + } + } + } + try { + fn(); + } finally { + if (fd !== null) { + try { + fs2.closeSync(fd); + fs2.unlinkSync(lock); + } catch { + } + } + } +} +function readSessionRegistry(dataRoot) { + try { + const parsed = JSON.parse(fs2.readFileSync(sessionMapPath(dataRoot), "utf8")); + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return parsed; + } catch { + return {}; + } +} +function upsertSessionEntry(dataRoot, sessionId, patch) { + const file = sessionMapPath(dataRoot); + try { + fs2.mkdirSync(path2.dirname(file), { recursive: true }); + withRegistryLock(dataRoot, () => { + let registry2 = {}; + try { + const parsed = JSON.parse(fs2.readFileSync(file, "utf8")); + if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) { + registry2 = parsed; + } + } catch (err) { + if (err.code !== "ENOENT") { + try { + fs2.renameSync(file, `${file}.corrupt-${Date.now()}`); + } catch { + } + } + } + const key = safeSessionKey(sessionId); + const prior = registry2[key] ?? {}; + registry2[key] = { ...prior, ...patch, session_id: sessionId }; + const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`; + const fd = fs2.openSync(tmp, "w", 384); + try { + fs2.writeFileSync(fd, JSON.stringify(registry2, null, 2)); + fs2.fsyncSync(fd); + } finally { + fs2.closeSync(fd); + } + fs2.renameSync(tmp, file); + }); + } catch { + } +} + +// src/coord/paths.ts +import { createHash } from "node:crypto"; +import fs3 from "node:fs"; +import path3 from "node:path"; +import os2 from "node:os"; +var MAX_SOCKET_PATH = 96; +function teamPaths(dataRoot, teamId) { + const teamsRoot = path3.join(dataRoot, "teams"); + const teamDir = path3.join(teamsRoot, safeTeamId(teamId)); + return { + dataRoot, + teamId, + teamDir, + eventsFile: path3.join(teamDir, "events.jsonl"), + checkpointFile: path3.join(teamDir, "checkpoint.json"), + lockFile: path3.join(teamDir, "coordinator.lock"), + auditFile: path3.join(teamDir, "coordinator.audit.jsonl"), + socketCandidate: path3.join(teamDir, "coordinator.sock") + }; +} +function safeTeamId(teamId) { + const escaped = teamId.replace(/[^A-Za-z0-9._-]/g, (c) => "~" + c.codePointAt(0).toString(16)); + if (escaped === ".") return "~2e"; + if (escaped === "..") return "~2e2e"; + return escaped; +} +function assertPathInside(base, target) { + const resolvedBase = path3.resolve(base); + const resolvedTarget = path3.resolve(target); + if (resolvedTarget !== resolvedBase && !resolvedTarget.startsWith(resolvedBase + path3.sep)) { + throw new Error(`path escapes containment: ${target} (base: ${base})`); + } +} +function resolveSocketPath(teamDir) { + const candidate = path3.join(teamDir, "coordinator.sock"); + if (candidate.length <= MAX_SOCKET_PATH) { + return { socketPath: candidate, fallback: false, registryFile: path3.join(teamDir, "socket.path") }; + } + const hash = createHash("sha256").update(candidate).digest("hex").slice(0, 16); + const tmpRoot = fs3.realpathSync(os2.tmpdir()); + const fallbackDir = path3.join(tmpRoot, "agent-team-sockets"); + fs3.mkdirSync(fallbackDir, { recursive: true, mode: 448 }); + try { + fs3.chmodSync(fallbackDir, 448); + } catch { + } + const fallbackPath = path3.join(fallbackDir, `at-${hash}.sock`); + return { socketPath: fallbackPath, fallback: true, registryFile: path3.join(teamDir, "socket.path") }; +} +function discoverSocketPath(teamDir) { + const registryFile = path3.join(teamDir, "socket.path"); + try { + const registered = fs3.readFileSync(registryFile, "utf8").trim(); + if (registered.length > 0) return registered; + } catch { + } + return resolveSocketPath(teamDir).socketPath; +} + +// src/coord/rpc.ts +import net from "node:net"; +import fs4 from "node:fs"; +import path4 from "node:path"; +var COORDINATOR_UNAVAILABLE_MESSAGE = "Agent Teams coordinator is unavailable (between coordinators); retry the request shortly"; +var MAX_RPC_BUFFER_BYTES = 1 << 20; +var RpcClient = class _RpcClient { + constructor(socket, token = void 0, nextId = 1, pending = /* @__PURE__ */ new Map(), maxFrameBytes = MAX_RPC_BUFFER_BYTES) { + this.socket = socket; + this.token = token; + this.nextId = nextId; + this.pending = pending; + this.maxFrameBytes = maxFrameBytes; + } + maxFrameBytes; + static async connect(socketPath, opts = {}) { + const timeoutMs = opts.timeoutMs ?? 3e3; + const socket = await new Promise((resolve, reject) => { + const s = net.connect(socketPath, () => resolve(s)); + s.setEncoding("utf8"); + const timer = setTimeout(() => { + s.destroy(); + reject(new Error(`rpc connect timeout after ${timeoutMs}ms: ${socketPath}`)); + }, timeoutMs); + s.once("error", (err) => { + clearTimeout(timer); + reject(err); + }); + resolveSocketOnConnect(s, () => clearTimeout(timer)); + }); + const client = new _RpcClient(socket, opts.token, 1, /* @__PURE__ */ new Map(), opts.maxFrameBytes); + socket.on("data", (chunk) => client.onData(chunk)); + socket.on("close", () => client.failAll(new Error("rpc connection closed"))); + socket.on("error", (err) => client.failAll(err)); + return client; + } + async call(method, params, opts = {}) { + const id = this.nextId++; + const timeoutMs = opts.timeoutMs ?? 15e3; + if (opts.signal?.aborted) { + return Promise.reject( + new TeamError("TEAM_WAIT_ABORTED", `wait_agent aborted: ${abortReasonText(opts.signal.reason)}`) + ); + } + const payload = JSON.stringify({ id, method, params, ...this.token !== void 0 ? { token: this.token } : {} }) + "\n"; + return new Promise((resolve, reject) => { + let settled = false; + let timer; + const finish = (fn) => { + if (settled) return; + settled = true; + clearTimeout(timer); + opts.signal?.removeEventListener("abort", onAbort); + this.pending.delete(id); + fn(); + }; + const onAbort = () => { + finish( + () => reject(new TeamError("TEAM_WAIT_ABORTED", `wait_agent aborted: ${abortReasonText(opts.signal?.reason)}`)) + ); + this.socket.destroy(); + }; + timer = setTimeout(() => { + finish(() => reject(new Error(`rpc call ${method} timed out after ${timeoutMs}ms`))); + }, timeoutMs); + this.pending.set(id, { + resolve: (v) => finish(() => resolve(v)), + reject: (e) => finish(() => reject(e)) + }); + opts.signal?.addEventListener("abort", onAbort, { once: true }); + this.socket.write(payload, (err) => { + if (err) finish(() => reject(err)); + }); + }); + } + close() { + this.socket.destroy(); + } + onData(chunk) { + this.buffer += chunk; + if (Buffer.byteLength(this.buffer, "utf8") > this.maxFrameBytes) { + this.failAll(new Error(`rpc response frame exceeds ${this.maxFrameBytes} bytes`)); + this.socket.destroy(); + return; + } + let nl; + while ((nl = this.buffer.indexOf("\n")) !== -1) { + const line = this.buffer.slice(0, nl); + this.buffer = this.buffer.slice(nl + 1); + if (line.trim().length === 0) continue; + try { + this.onResponse(JSON.parse(line)); + } catch { + this.failAll(new Error("invalid rpc response frame")); + } + } + } + buffer = ""; + onResponse(res) { + const entry = this.pending.get(res.id); + if (entry === void 0) return; + this.pending.delete(res.id); + if (res.ok) { + entry.resolve(res.result); + } else if (res.error?.code !== void 0) { + entry.reject(new TeamError(res.error.code, res.error.message)); + } else { + const err = new Error(res.error?.message ?? "rpc error"); + if (res.error?.name) err.name = res.error.name; + entry.reject(err); + } + } + failAll(err) { + for (const [, entry] of this.pending) entry.reject(err); + this.pending.clear(); + } +}; +function resolveSocketOnConnect(socket, onConnected) { + socket.once("connect", onConnected); +} +function rpcTokenPath(teamDir) { + return path4.join(teamDir, "rpc.token"); +} +function readRpcToken(teamDir) { + try { + const token = fs4.readFileSync(rpcTokenPath(teamDir), "utf8").trim(); + return token.length > 0 ? token : void 0; + } catch { + return void 0; + } +} +function coordinatorUnavailableError(detail) { + return new TeamError("TEAM_DISPOSED", COORDINATOR_UNAVAILABLE_MESSAGE, { cause: detail }); +} +function abortReasonText(reason) { + if (reason instanceof Error) return reason.message; + if (reason === void 0 || reason === null) return "aborted"; + return String(reason); +} +async function callCoordinator(teamDir, teamId, method, params, opts = {}) { + const socketPath = discoverSocketPath(teamDir); + const token = readRpcToken(teamDir); + const client = await RpcClient.connect(socketPath, { + timeoutMs: opts.connectTimeoutMs ?? 1e3, + ...token !== void 0 ? { token } : {} + }).catch((err) => { + throw coordinatorUnavailableError(`socket ${socketPath}: ${err.code ?? err.message}`); + }); + try { + return await client.call(method, params, { + timeoutMs: opts.timeoutMs, + ...opts.signal !== void 0 ? { signal: opts.signal } : {} + }); + } finally { + client.close(); + } +} + +// src/hooks/inbox.ts +import fs7 from "node:fs"; +import path7 from "node:path"; + +// src/coord/replay.ts +import fs5 from "node:fs"; +import path5 from "node:path"; +var checkpointDocSchema = external_exports.strictObject({ + kind: external_exports.literal("agent-team-checkpoint"), + stateVersion: external_exports.literal(TEAM_PROJECTION_STATE_VERSION), + lastSeq: external_exports.number().int().nonnegative(), + lastOffset: external_exports.number().int().nonnegative(), + savedAt: external_exports.string(), + state: teamStateSchema, + view: external_exports.unknown() +}); +function checkpointPath(teamDir) { + return path5.join(teamDir, "checkpoint.json"); +} +async function load(teamDir, teamId) { + const startedAt = Date.now(); + const eventsFile = path5.join(teamDir, "events.jsonl"); + const raw2 = readBufferOrEmpty(eventsFile); + let checkpointIgnored; + let doc; + try { + const rawDoc = fs5.readFileSync(checkpointPath(teamDir), "utf8"); + const parsed = checkpointDocSchema.safeParse(JSON.parse(rawDoc)); + if (!parsed.success) { + checkpointIgnored = `checkpoint invalid: ${parsed.error.issues[0]?.message ?? "schema mismatch"}`; + } else if (parsed.data.state.id !== teamId) { + checkpointIgnored = `checkpoint teamId mismatch (${parsed.data.state.id} != ${teamId})`; + } else { + doc = parsed.data; + } + } catch { + } + const writers = []; + let state = emptyTeamState(teamId); + let seq = 0; + let fromCheckpoint = false; + let corrupt; + if (doc !== void 0) { + const tail = raw2.subarray(doc.lastOffset); + const first = firstLineBytes(tail); + if (tail.length > 0 && first === void 0) { + checkpointIgnored = "checkpoint offset desync (tail not line-aligned) \u2014 full replay"; + } else if (first !== void 0 && JSON.parse(first.parsed).seq !== doc.lastSeq + 1) { + checkpointIgnored = "checkpoint offset desync (seq continuity broken) \u2014 full replay"; + } else { + state = doc.state; + seq = doc.lastSeq; + fromCheckpoint = true; + } + } + const startOffset = fromCheckpoint && doc !== void 0 ? doc.lastOffset : 0; + let offset = startOffset; + let consumeRest = true; + while (consumeRest && offset < raw2.length) { + const nl = raw2.indexOf(10, offset); + if (nl === -1) { + corrupt = { line: seq + 1, reason: "trailing partial line (no newline)" }; + state = withFailure(state, raw2.subarray(offset).toString("utf8")); + seq += 1; + consumeRest = false; + break; + } + const lineText = raw2.subarray(offset, nl).toString("utf8"); + const lineNo = seq + 1; + offset = nl + 1; + if (lineText.length === 0) { + corrupt = { line: lineNo, reason: "empty line" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + let parsed; + try { + parsed = JSON.parse(lineText); + } catch { + corrupt = { line: lineNo, reason: "invalid JSON" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + const line = parsed; + if (typeof line.writer === "string" && !writers.includes(line.writer)) writers.push(line.writer); + if (typeof parsed !== "object" || parsed === null || typeof parsed.seq !== "number" || !("event" in parsed) || parsed.seq !== lineNo) { + corrupt = { line: lineNo, reason: "line shape invalid or seq discontinuous" }; + state = withFailure(state, lineText); + seq = lineNo; + consumeRest = false; + break; + } + state = applyProjectionEvent(state, line.event); + seq = lineNo; + if (state.failure !== void 0) { + consumeRest = false; + } + } + return { + state, + view: teamProjectionView(state), + seq, + fromCheckpoint, + checkpointIgnored, + corrupt, + writers, + replayMs: Date.now() - startedAt + }; +} +function readBufferOrEmpty(file) { + try { + return fs5.readFileSync(file); + } catch { + return Buffer.alloc(0); + } +} +function firstLineBytes(buf) { + const nl = buf.indexOf(10); + const first = (nl === -1 ? buf : buf.subarray(0, nl)).toString("utf8"); + if (first.length === 0) return void 0; + try { + JSON.parse(first); + return { parsed: first }; + } catch { + return void 0; + } +} +function withFailure(state, rawLine) { + const m = rawLine.match(/"type"\s*:\s*"(team\/[A-Za-z/-]+)"/); + const type = m?.[1] ?? "stream"; + return { ...state, failure: `persisted Agent Teams ${type} payload is invalid` }; +} + +// src/provider/member-files.ts +import fs6 from "node:fs"; +import path6 from "node:path"; +function teamEverCreated(teamDir, leadSessionId) { + let entries; + try { + entries = fs6.readdirSync(path6.join(teamDir, "members")); + } catch { + return false; + } + return entries.some((entry) => entry !== leadSessionId); +} +function memberPaths(teamDir, memberId) { + const memberDir = path6.join(teamDir, "members", memberId); + const runDir = path6.join(memberDir, "run"); + return { + memberDir, + originFile: path6.join(memberDir, "origin.json"), + receiptsFile: path6.join(memberDir, "receipts.jsonl"), + stopBudgetFile: path6.join(memberDir, "stop-budget.json"), + runDir, + currentFile: path6.join(runDir, "current.json"), + drainMarkerFile: path6.join(runDir, "drain-requested.json"), + modelFailedFile: path6.join(memberDir, "model-failed.json") + }; +} +function writeJsonAtomic(file, value) { + fs6.mkdirSync(path6.dirname(file), { recursive: true, mode: 448 }); + const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; + const fd = fs6.openSync(tmp, "w", 384); + try { + fs6.writeFileSync(fd, JSON.stringify(value, null, 2)); + fs6.fsyncSync(fd); + } finally { + fs6.closeSync(fd); + } + fs6.renameSync(tmp, file); +} +function readJson(file) { + let raw2; + try { + raw2 = fs6.readFileSync(file, "utf8"); + } catch (err) { + if (err.code === "ENOENT") return void 0; + throw err; + } + return JSON.parse(raw2); +} +function appendReceipt(paths, receipt) { + fs6.mkdirSync(path6.dirname(paths.receiptsFile), { recursive: true, mode: 448 }); + const fd = fs6.openSync(paths.receiptsFile, "a", 384); + try { + fs6.writeFileSync(fd, JSON.stringify(receipt) + "\n"); + fs6.fsyncSync(fd); + } finally { + fs6.closeSync(fd); + } +} +function readReceipts(paths) { + let raw2; + try { + raw2 = fs6.readFileSync(paths.receiptsFile, "utf8"); + } catch (err) { + if (err.code === "ENOENT") return []; + throw err; + } + const receipts = []; + for (const line of raw2.split("\n")) { + if (line.trim().length === 0) continue; + receipts.push(JSON.parse(line)); + } + return receipts; +} +function receiptMessageIds(paths) { + return new Set(readReceipts(paths).map((r) => r.messageId)); +} +function readStopBudget(paths) { + return readJson(paths.stopBudgetFile); +} +function writeStopBudget(paths, budget) { + writeJsonAtomic(paths.stopBudgetFile, budget); +} + +// src/provider/framing.ts +function renderFramed(framedJson) { + const blocks = JSON.parse(framedJson); + if (!Array.isArray(blocks) || blocks.length === 0) { + throw new Error("framed message must be a non-empty JSON array of content blocks"); + } + const header = blocks[0]; + if (header.type !== "text" || typeof header.text !== "string") { + throw new Error("framed message first block must be the text header"); + } + const m = header.text.match(/^Team message from (.+):$/); + if (m === null) { + throw new Error(`framed message header mismatch: ${JSON.stringify(header.text)}`); + } + const lines = [header.text]; + for (const block of blocks.slice(1)) { + if (block.type === "text" && typeof block.text === "string") { + lines.push(block.text); + } else { + lines.push(JSON.stringify(block)); + } + } + return { messageId: "", senderName: m[1], text: lines.join("\n") }; +} + +// src/hooks/inbox.ts +function resolveHookRole(args) { + const entry = args.registryEntry; + if (entry?.role === "teammate" && typeof entry.teamId === "string" && entry.teamId.length > 0) { + return { + role: "teammate", + teamId: entry.teamId, + name: typeof entry.name === "string" && entry.name.length > 0 ? entry.name : "teammate", + ...typeof entry.memberId === "string" && entry.memberId.length > 0 ? { memberId: entry.memberId } : {} + }; + } + const hint = parseSpawnIdentity(args.spawnIdentityEnv); + if (hint !== void 0) return { role: "teammate", teamId: hint.teamId, name: hint.name, memberId: hint.memberId, hint }; + return { role: "lead", teamId: args.sessionId, name: "lead" }; +} +function parseSpawnIdentity(raw2) { + if (raw2 === void 0 || raw2.trim().length === 0) return void 0; + try { + const parsed = JSON.parse(raw2); + if (typeof parsed.teamId === "string" && parsed.teamId.length > 0 && typeof parsed.memberId === "string" && parsed.memberId.length > 0 && typeof parsed.name === "string" && parsed.name.length > 0) { + return { teamId: parsed.teamId, memberId: parsed.memberId, name: parsed.name }; + } + } catch { + } + return void 0; +} +async function pendingForLead(teamDir, teamId) { + if (!fs7.existsSync(path7.join(teamDir, "events.jsonl"))) return []; + const loaded = await load(teamDir, teamId); + return pendingLeadMessages(teamDir, loaded.state); +} +function pendingLeadMessages(teamDir, state) { + if (state.failure !== void 0) return []; + const teamId = state.id; + const delivered = new Set(state.delivered); + const receipted = receiptMessageIds(memberPaths(teamDir, teamId)); + const pending = []; + for (const message of state.messages) { + if (message.targetId !== teamId || delivered.has(message.id) || receipted.has(message.id)) continue; + const framed = [ + { type: "text", text: `Team message from ${message.senderName}:` }, + ...message.content + ]; + pending.push({ + messageId: message.id, + senderName: message.senderName, + text: renderFramed(JSON.stringify(framed)).text + }); + } + return pending; +} +function buildStopReason(texts) { + return `[agent-team inbox] \u65B0\u6D88\u606F\u5230\u8FBE\uFF0C\u672C\u8F6E\u7ED3\u675F\u540E\u9700\u5904\u7406\uFF1A +${texts.join("\n\n")}`; +} +function buildInboxContext(texts) { + return `[agent-team inbox] \u5F85\u6536\u6D88\u606F ${texts.length} \u6761\uFF1A +${texts.join("\n\n")}`; +} +function writeReceipts(dataRoot, teamId, messageIds, channel) { + const paths = memberPaths(teamPaths(dataRoot, teamId).teamDir, teamId); + for (const messageId of messageIds) { + appendReceipt(paths, { messageId, channel, ts: (/* @__PURE__ */ new Date()).toISOString() }); + } +} +function runKeyFor(stopHookActive) { + return stopHookActive ? "continuation" : "fresh-run"; +} +function effectiveBlocks(state, runKey) { + if (runKey === "fresh-run") return 0; + return state?.blocks ?? 0; +} +function budgetAllows(state, runKey) { + return effectiveBlocks(state, runKey) < 3; +} +function nextBudget(state, runKey) { + return { runKey, blocks: effectiveBlocks(state, runKey) + 1 }; +} + +// src/provider/lead-wake.ts +import fs8 from "node:fs"; +import path9 from "node:path"; + +// src/provider/procgroup.ts +import path8 from "node:path"; +import { fileURLToPath } from "node:url"; +var HELPER_DEFAULT = path8.join(path8.dirname(fileURLToPath(import.meta.url)), "detach-helper.mjs"); + +// src/provider/lead-wake.ts +function leadDir(teamDir) { + return path9.join(teamDir, "lead"); +} +function leadStatePath(teamDir) { + return path9.join(leadDir(teamDir), "state.json"); +} +function readLeadState(teamDir) { + try { + const parsed = JSON.parse(fs8.readFileSync(leadStatePath(teamDir), "utf8")); + if (typeof parsed.active !== "boolean" || typeof parsed.updatedAt !== "string") return void 0; + return parsed; + } catch { + return void 0; + } +} +function writeLeadState(teamDir, state) { + const dir = leadDir(teamDir); + fs8.mkdirSync(dir, { recursive: true }); + const file = leadStatePath(teamDir); + const tmp = `${file}.tmp-${process.pid}`; + const fd = fs8.openSync(tmp, "w", 384); + try { + fs8.writeFileSync(fd, JSON.stringify(state, null, 2)); + fs8.fsyncSync(fd); + } finally { + fs8.closeSync(fd); + } + fs8.renameSync(tmp, file); +} +function soloAnchors(prior) { + return { + ...prior?.soloNotifiedAt !== void 0 ? { soloNotifiedAt: prior.soloNotifiedAt } : {}, + ...prior?.soloNotifiedVia !== void 0 ? { soloNotifiedVia: prior.soloNotifiedVia } : {}, + ...prior?.soloRetractedAt !== void 0 ? { soloRetractedAt: prior.soloRetractedAt } : {} + }; +} +function writableState(teamDir) { + try { + fs8.accessSync(leadStatePath(teamDir)); + } catch { + return true; + } + return readLeadState(teamDir) !== void 0; +} +function recordLeadTurnEvent(teamDir, event2, now = Date.now()) { + try { + if (!writableState(teamDir)) return; + const prior = readLeadState(teamDir); + writeLeadState(teamDir, { + ...prior?.lastWakeAt !== void 0 ? { lastWakeAt: prior.lastWakeAt } : {}, + ...soloAnchors(prior), + active: event2 === "start", + updatedAt: new Date(now).toISOString() + }); + } catch { + } +} +function markSoloNotified(teamDir, now = Date.now(), via = "db") { + try { + if (!writableState(teamDir)) return; + const prior = readLeadState(teamDir); + const at = new Date(now).toISOString(); + writeLeadState(teamDir, { + ...prior?.lastWakeAt !== void 0 ? { lastWakeAt: prior.lastWakeAt } : {}, + ...soloAnchors(prior), + active: prior?.active ?? false, + updatedAt: at, + soloNotifiedAt: at, + soloNotifiedVia: via + }); + } catch { + } +} +function markSoloRetracted(teamDir, now = Date.now()) { + try { + if (!writableState(teamDir)) return; + const prior = readLeadState(teamDir); + const at = new Date(now).toISOString(); + writeLeadState(teamDir, { + ...prior?.lastWakeAt !== void 0 ? { lastWakeAt: prior.lastWakeAt } : {}, + ...soloAnchors(prior), + active: prior?.active ?? false, + updatedAt: at, + soloRetractedAt: at + }); + } catch { + } +} + +// src/provider/transcript.ts +import fs9 from "node:fs"; +import os3 from "node:os"; +import path10 from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +// src/provider/model-selection.ts +function parseModelSelection(value) { + if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0; + const record = value; + const providerId = nonEmptyString(record.providerId); + const modelId = nonEmptyString(record.modelId); + if (providerId === void 0 || modelId === void 0) return void 0; + const options = record.options; + if (options !== void 0 && (typeof options !== "object" || options === null || Array.isArray(options))) { + return void 0; + } + let reasoningLevel; + const rawLevel = options !== void 0 ? options.reasoningLevel : record.reasoningLevel; + if (rawLevel !== void 0) { + reasoningLevel = nonEmptyString(rawLevel); + if (reasoningLevel === void 0) return void 0; + } + return { providerId, modelId, ...reasoningLevel !== void 0 ? { reasoningLevel } : {} }; +} +function nonEmptyString(value) { + if (typeof value !== "string") return void 0; + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : void 0; +} + +// src/provider/transcript.ts +function defaultDbPath() { + return process.env.TEAM_DB_PATH ?? path10.join(os3.homedir(), ".zcode", "cli", "db", "db.sqlite"); +} +var TranscriptReader = class { + dbPath; + db = null; + dbMissing = false; + constructor(deps = {}) { + this.dbPath = deps.dbPath ?? defaultDbPath(); + } + get path() { + return this.dbPath; + } + /** 库不存在 = 空库语义(探针方法走缺省值,不建临时库)。 */ + missing() { + if (!this.dbMissing) this.dbMissing = !fs9.existsSync(this.dbPath); + else if (!fs9.existsSync(this.dbPath)) return true; + else this.dbMissing = false; + return this.dbMissing; + } + open() { + if (this.db !== null) return this.db; + if (!fs9.existsSync(this.dbPath)) { + throw new Error("transcript db missing"); + } + this.db = new DatabaseSync(this.dbPath, { readOnly: true }); + return this.db; + } + close() { + this.db?.close(); + this.db = null; + } + /** 会话行实查;不存在 → undefined;读失败 → 抛错。 */ + session(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + "SELECT id, parent_id, directory, task_type, title, time_created FROM session WHERE id = ?" + ).get(sessionId); + return row ?? void 0; + } + /** 找「目录 = cwd 且创建于 sinceMs 之后、首条真实用户文本 = firstPrompt」的会话(fresh spawn 探针)。 */ + findSessionByFirstPrompt(args) { + if (this.missing()) return void 0; + const rows = this.open().prepare( + "SELECT id, time_created FROM session WHERE directory = ? AND time_created >= ? ORDER BY time_created ASC" + ).all(args.cwd, args.sinceMs - 2e3); + for (const row of rows) { + if (args.excludeSessionIds?.has(row.id)) continue; + const first = this.firstRealUserText(row.id); + if (first === args.firstPrompt) return row.id; + } + return void 0; + } + /** 首条「真实用户」消息的文本部分(跳过 hook/系统注入的 model-only 消息)。 */ + firstRealUserText(sessionId) { + if (this.missing()) return null; + const rows = this.open().prepare( + `SELECT p.data pdata FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + ORDER BY m.sequence, p.sequence LIMIT 1` + ).all(sessionId); + if (rows.length === 0) return null; + return extractText(rows[0].pdata); + } + /** 会话中是否已存在该文本的「真实用户」消息(delivered/去重探针:prompt 逐字落库)。 */ + hasUserText(sessionId, text) { + if (this.missing()) return false; + const row = this.open().prepare( + `SELECT COUNT(*) n FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + AND json_extract(p.data,'$.text') = ? LIMIT 1` + ).get(sessionId, text); + return row.n > 0; + } + /** 会话全部「真实用户」文本消息(时间序;轮次 prompt 审计/恰一次检索用)。 */ + realUserTexts(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.id mid, m.time_created tc, p.data pdata, + json_extract(m.data,'$.semantics.origin') origin, + json_extract(m.data,'$.modelSelection.modelId') model + FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(p.data,'$.type') = 'text' + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + return rows.map((r) => ({ + messageId: r.mid, + text: extractText(r.pdata) ?? "", + timeCreated: r.tc, + origin: r.origin, + modelId: r.model + })); + } + /** 会话最新使用的模型(成员行 model 字段实查;无消息 → undefined)。 */ + latestModel(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT json_extract(m.data,'$.modelSelection.modelId') model FROM message m + WHERE m.session_id = ? AND json_extract(m.data,'$.modelSelection.modelId') IS NOT NULL + ORDER BY m.sequence DESC LIMIT 1` + ).get(sessionId); + return row?.model; + } + /** + * 最近一条「真实用户提交」(semantics.origin=real_user)消息携带的模型快照 + 提交时间。 + * 0.4.0 三源判定的「提交证据」:宿主保存用户消息时写入该次提交的 modelSelection(本机源码核对), + * 输入框切换在提交瞬间即体现在这里——不依赖会话选模条目(issue #7 场景它可能滞后)。 + * hook/系统注入的 user 消息(origin≠real_user)不算提交。 + */ + latestSubmissionSelection(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT m.time_created tc, + json_extract(m.data,'$.modelSelection.providerId') p, + json_extract(m.data,'$.modelSelection.modelId') mo, + json_extract(m.data,'$.modelSelection.options.reasoningLevel') lvl + FROM message m + WHERE m.session_id = ? AND json_extract(m.data,'$.role') = 'user' + AND json_extract(m.data,'$.semantics.origin') = 'real_user' + AND json_extract(m.data,'$.modelSelection.providerId') IS NOT NULL + AND json_extract(m.data,'$.modelSelection.modelId') IS NOT NULL + ORDER BY m.time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.p.trim(); + const modelId = row.mo.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const lvl = typeof row.lvl === "string" ? row.lvl.trim() : ""; + return { + selection: { providerId, modelId, ...lvl.length > 0 ? { reasoningLevel: lvl } : {} }, + at: row.tc + }; + } + /** 会话选模条目 + 生效时间(UPSERT 单行;用于与提交快照比较「后来是否有 /model 修改」)。 */ + latestModelSelectionTimed(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT data, MAX(COALESCE(time_updated, time_created), time_created) at FROM session_entry + WHERE session_id = ? AND type = 'runtime/model_selection' + ORDER BY time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const selection = this.latestModelSelection(sessionId); + if (selection === void 0) return void 0; + return { selection, at: row.at }; + } + /** + * 最近一次**主轮**实际模型调用(+ 开始时间)。query_source='main_turn' 过滤是 0.4.0 关键口径: + * compact/标题生成/goal 摘要/subagent/workflow 子轮的行属于辅助模型,绝不能当作 Lead 当前模型 + * (实测本机取值域 = compact, goal_summary_title, main_turn, session_title, subagent, + * target_completion_verification, workflow_child)。 + */ + latestMainTurnUsage(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT provider_id, model_id, variant, started_at FROM model_usage + WHERE session_id = ? AND query_source = 'main_turn' + ORDER BY started_at DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.provider_id.trim(); + const modelId = row.model_id.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const variant = typeof row.variant === "string" ? row.variant.trim() : ""; + return { + selection: { providerId, modelId, ...variant.length > 0 ? { reasoningLevel: variant } : {} }, + at: row.started_at + }; + } + /** + * 会话库中最近一次 setModel 的选择(Round A 实证:条目为 UPSERT 单行,canonical id + * `:runtime-model-selection`,时间排序安全)。data 取嵌套 modelSelection 优先; + * 兼容旧行把 providerId/modelId/thoughtLevel 平铺在顶层的形态。 + */ + latestModelSelection(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT data FROM session_entry + WHERE session_id = ? AND type = 'runtime/model_selection' + ORDER BY time_created DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const data = parseOrNull(row.data); + if (data === null) return void 0; + const nested = parseModelSelection(data.modelSelection); + if (nested !== void 0) return nested; + const providerId = typeof data.providerId === "string" ? data.providerId.trim() : ""; + const modelId = typeof data.modelId === "string" ? data.modelId.trim() : ""; + if (providerId.length === 0 || modelId.length === 0) return void 0; + const thoughtLevel = typeof data.thoughtLevel === "string" ? data.thoughtLevel.trim() : ""; + return { + providerId, + modelId, + ...thoughtLevel.length > 0 ? { reasoningLevel: thoughtLevel } : {} + }; + } + /** 最近一次真实模型调用(session_entry 缺失时的继承兜底;variant = 思考强度)。 */ + latestModelUsage(sessionId) { + if (this.missing()) return void 0; + const row = this.open().prepare( + `SELECT provider_id, model_id, variant FROM model_usage + WHERE session_id = ? ORDER BY started_at DESC LIMIT 1` + ).get(sessionId); + if (row === void 0) return void 0; + const providerId = row.provider_id.trim(); + const modelId = row.model_id.trim(); + if (providerId.length === 0 || modelId.length === 0) return void 0; + const variant = typeof row.variant === "string" ? row.variant.trim() : ""; + return { + providerId, + modelId, + ...variant.length > 0 ? { reasoningLevel: variant } : {} + }; + } + /** 完成回合导出(D3 fork 转录):真实用户消息 + 助手文本;tool 部分记工具名。 */ + exportTurns(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.data mdata, p.data pdata FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + const turns = []; + for (const r of rows) { + const message = parseOrNull(r.mdata); + const part = parseOrNull(r.pdata); + if (message === null || part === null) continue; + const isUser = message.role === "user"; + const isAssistant = message.role === "assistant"; + const realUser = isUser && message.semantics?.origin === "real_user"; + if (part.type === "text" && typeof part.text === "string") { + if (realUser) turns.push({ role: "user", text: part.text, toolNames: [] }); + else if (isAssistant) turns.push({ role: "assistant", text: part.text, toolNames: [] }); + } else if (isAssistant && part.type === "tool" && typeof part.tool === "string") { + const last = turns[turns.length - 1]; + if (last !== void 0 && last.role === "assistant" && !last.toolNames.length) { + last.toolNames.push(part.tool); + } else { + turns.push({ role: "assistant", text: "", toolNames: [part.tool] }); + } + } + } + return turns; + } + /** + * T5.7 成员会话查看视图导出(detail 合成数据源;只读、走 session_id 索引): + * 时间序全量 part 行(text/tool 两型;其余 part 型跳过),损坏行跳过。 + * 与 exportTurns 的区别:保留每条 part 的时间戳/role/工具状态(面板折叠行渲染), + * 不做回合聚合;hook 注入文本不落 transcript part(H14),framed 徽标由 + * panel/detail.ts 以 events 回填(不改写原文)。 + */ + exportDetailParts(sessionId) { + if (this.missing()) return []; + const rows = this.open().prepare( + `SELECT m.data mdata, m.time_created mtc, p.data pdata, p.time_created ptc + FROM message m JOIN part p ON p.message_id = m.id + WHERE m.session_id = ? + ORDER BY m.sequence, p.sequence` + ).all(sessionId); + const out2 = []; + for (const r of rows) { + const message = parseOrNull(r.mdata); + const part = parseOrNull(r.pdata); + if (message === null || part === null) continue; + const role2 = message.role === "user" ? "user" : message.role === "assistant" ? "assistant" : void 0; + if (role2 === void 0) continue; + if (role2 === "user" && message.semantics?.origin !== "real_user") continue; + const ts2 = typeof r.ptc === "number" ? r.ptc : r.mtc; + if (part.type === "text" && typeof part.text === "string") { + out2.push({ ts: ts2, role: role2, kind: "text", text: part.text }); + } else if (part.type === "tool" && typeof part.tool === "string") { + const status = typeof part.state?.status === "string" ? part.state.status : "unknown"; + out2.push({ + ts: ts2, + role: "assistant", + kind: "toolCall", + toolName: part.tool, + toolStatus: status, + ...part.state?.input !== void 0 ? { toolInput: part.state.input } : {}, + ...part.state?.output !== void 0 ? { toolOutput: part.state.output } : {} + }); + } + } + return out2; + } +}; +function parseOrNull(raw2) { + try { + return JSON.parse(raw2); + } catch { + return null; + } +} +function extractText(partData) { + try { + const part = JSON.parse(partData); + return typeof part.text === "string" ? part.text : null; + } catch { + return null; + } +} + +// src/provider/lead-model-probe.ts +var PLAN_PREFIXES = ["account:", "builtin:"]; +function isPlanPrefix(providerId) { + return PLAN_PREFIXES.some((prefix) => providerId.startsWith(prefix)); +} +function probeLeadPlanModel(sessionId, dbPath, modelHint) { + const hint = typeof modelHint === "string" ? modelHint.trim() : ""; + if (hint.length > 0) { + return isPlanPrefix(hint) ? { blocked: true, model: hint, evidence: "hint" } : { blocked: false, evidence: "hint" }; + } + try { + const reader = new TranscriptReader({ dbPath: dbPath ?? defaultDbPath() }); + try { + const sources = [ + reader.latestSubmissionSelection(sessionId), + reader.latestModelSelectionTimed(sessionId), + reader.latestMainTurnUsage(sessionId) + ].filter((source) => source !== void 0); + if (sources.length === 0) return { blocked: false, evidence: "none" }; + const latest = sources.reduce((a, b) => b.at > a.at ? b : a).selection; + const isOfficialPlan = isPlanPrefix(latest.providerId); + return isOfficialPlan ? { blocked: true, model: `${latest.providerId}/${latest.modelId}`, evidence: "db" } : { blocked: false, evidence: "db" }; + } finally { + reader.close(); + } + } catch { + return { blocked: false, evidence: "none" }; + } +} + +// src/hooks.ts +function readStdin() { + try { + return fs10.readFileSync(0, "utf8"); + } catch { + return ""; + } +} +var raw = readStdin(); +var input = {}; +try { + input = raw ? JSON.parse(raw) : {}; +} catch { + input = { parse_error: true, raw_preview: raw.slice(0, 500) }; +} +var DATA = dataDir(); +ensureDir(path11.join(DATA, "logs")); +var event = (input.hook_event_name ?? process.env.ZCODE_HOOK_EVENT ?? "unknown").toLowerCase(); +var envOverlay = {}; +for (const k of Object.keys(process.env)) { + if (k.startsWith("ZCODE_") || k.startsWith("CLAUDE_") || k.startsWith("TEAM_")) { + envOverlay[k] = isSensitiveEnvKey(k) ? "" : process.env[k]; + } +} +var rawSessionId = input.session_id ?? process.env.ZCODE_SESSION_ID ?? process.env.CLAUDE_SESSION_ID ?? null; +var promptText = input.prompt ? String(input.prompt) : null; +function modelCategory(model) { + if (typeof model !== "string" || model.trim().length === 0) return null; + if (model.startsWith("account:")) return "account"; + if (model.startsWith("builtin:")) return "builtin"; + return "custom"; +} +var logLine = { + ts: ts(), + event, + input_session_id: input.session_id ?? null, + env_session_id: process.env.ZCODE_SESSION_ID ?? process.env.CLAUDE_SESSION_ID ?? null, + env_overlay: envOverlay, + cwd: input.cwd ?? process.cwd(), + stop_hook_active: input.stop_hook_active ?? null, + // 不落 prompt 原文(可能含私有任务/代码);只记长度供排障。 + prompt_chars: promptText !== null ? promptText.length : null, + source: input.source ?? null, + // 〔D30〕宿主是否下发 model + 其形态(account/builtin/custom/null)。只记分类、不记 model; + // 让「startup 能否凭载荷判定套餐」从源码推断变成日志实证。 + model_category: modelCategory(input.model) +}; +appendJsonl(path11.join(DATA, "logs", "hooks.jsonl"), logLine); +var registry = readSessionRegistry(DATA); +var sessionKey = rawSessionId !== null ? safeSessionKey(rawSessionId) : ""; +var selfEntry = rawSessionId !== null ? registry[sessionKey] : void 0; +var role = resolveHookRole({ + registryEntry: selfEntry, + spawnIdentityEnv: process.env.TEAM_SPAWN_IDENTITY, + sessionId: rawSessionId ?? "" +}); +var runtimeConfig = readRuntimeConfig(); +var leadMode = validateLeadMode( + process.env.TEAM_LEAD_MODE !== void 0 ? process.env.TEAM_LEAD_MODE : readHostLeadModeOverride() ?? runtimeConfig?.leadMode +); +var leadOff = role.role === "lead" && leadMode === "off"; +function out(obj) { + return new Promise((resolve) => { + process.stdout.write(JSON.stringify(obj), () => resolve()); + }); +} +async function ackCoordinator(method, params) { + if (rawSessionId === null) return; + const teamDir = safeTeamDir(role.teamId); + if (teamDir === null) return; + await callCoordinator(teamDir, role.teamId, method, params, { timeoutMs: 2e3, connectTimeoutMs: 500 }).catch( + () => void 0 + ); +} +function safeTeamDir(teamId) { + if (!/^[A-Za-z0-9._-]+$/.test(teamId) || teamId === "." || teamId === "..") return null; + const { teamDir } = teamPaths(DATA, teamId); + try { + assertPathInside(path11.join(DATA, "teams"), teamDir); + } catch { + return null; + } + return teamDir; +} +async function boundedAck(method, params) { + await Promise.race([ + ackCoordinator(method, params), + new Promise((resolve) => setTimeout(resolve, 500)) + ]); +} +if (event === "sessionstart") { + if (rawSessionId !== null) { + const claim = role.role === "teammate" ? { + teamId: role.teamId, + role: "teammate", + name: role.name, + ...role.memberId !== void 0 ? { memberId: role.memberId } : {} + } : {}; + upsertSessionEntry(DATA, rawSessionId, { + ...selfEntry?.firstSeen === void 0 ? { firstSeen: ts() } : {}, + lastSeen: ts(), + event, + cwd: logLine.cwd, + hookRegistered: true, + ...claim + }); + } + const identityText = role.role === "teammate" ? identityTeammateText(role.name) : IDENTITY_LEAD_TEXT; + const interrupt = process.env.TEAM_INTERRUPT !== void 0 ? process.env.TEAM_INTERRUPT !== "false" : runtimeConfig?.interrupt ?? true; + let modeSection; + if (role.role === "lead") { + if (leadMode === "always") { + modeSection = ORCHESTRATOR_SECTION_TEXT; + } else if (leadMode === "auto") { + const teamDir = safeTeamDir(role.teamId); + if (teamDir !== null && teamEverCreated(teamDir, role.teamId)) { + modeSection = ON_DEMAND_SECTION_TEXT; + } + } + } + let context = buildSessionStartContext(identityText, interrupt, modeSection); + if (role.role === "lead" && !leadOff && rawSessionId !== null) { + const soloTeamDir = safeTeamDir(role.teamId); + if (soloTeamDir !== null) { + const soloState = readLeadState(soloTeamDir); + const modelHint = typeof input.model === "string" && input.model.trim().length > 0 ? input.model.trim() : void 0; + if (soloState?.soloNotifiedAt === void 0) { + const probe = probeLeadPlanModel(rawSessionId, void 0, modelHint); + if (probe.blocked) { + context += ` +${DEGRADED_SOLO_NOTE}`; + markSoloNotified(soloTeamDir, Date.now(), probe.evidence === "hint" ? "hint" : "db"); + } + } else if (soloState.soloRetractedAt === void 0) { + const recheck = probeLeadPlanModel(rawSessionId, void 0, modelHint); + if (recheck.evidence !== "none" && !recheck.blocked) { + context += ` +${SOLO_RETRACT_NOTE}`; + markSoloRetracted(soloTeamDir); + } + } + } + } + let pending = []; + if (role.role === "lead" && rawSessionId !== null) { + const teamDir = safeTeamDir(role.teamId); + if (teamDir !== null) { + recordLeadTurnEvent(teamDir, "start"); + if (!leadOff) { + pending = await pendingForLead(teamDir, role.teamId); + if (pending.length > 0) { + context += ` +${buildInboxContext(pending.map((m) => m.text))}`; + } + } + } + } + if (!leadOff) { + await out({ + hookSpecificOutput: { + hookEventName: "SessionStart", + additionalContext: context + } + }); + } + if (role.role === "lead" && rawSessionId !== null) { + if (!leadOff && pending.length > 0) { + writeReceipts(DATA, role.teamId, pending.map((m) => m.messageId), "sessionstart"); + await boundedAck("mailbox.ack", { session_id: rawSessionId, messageIds: pending.map((m) => m.messageId) }); + } + if (input.source === "resume") void ackCoordinator("admin.reconcile", { session_id: rawSessionId }); + } +} else if (event === "userpromptsubmit") { + if (role.role === "lead" && rawSessionId !== null) { + const teamDir = safeTeamDir(role.teamId); + if (teamDir !== null) { + recordLeadTurnEvent(teamDir, "start"); + const pending = leadOff ? [] : await pendingForLead(teamDir, role.teamId); + const soloState = readLeadState(teamDir); + let soloNeeded = false; + let soloRetractNeeded = false; + if (!leadOff) { + if (soloState?.soloNotifiedAt === void 0) { + soloNeeded = probeLeadPlanModel(rawSessionId).blocked; + } else if (soloState.soloRetractedAt === void 0) { + const recheck = probeLeadPlanModel(rawSessionId); + if (recheck.evidence === "db" && !recheck.blocked) soloRetractNeeded = true; + } + } + if (pending.length > 0 || soloNeeded || soloRetractNeeded) { + const parts = []; + if (soloRetractNeeded) parts.push(SOLO_RETRACT_NOTE); + if (soloNeeded) parts.push(DEGRADED_SOLO_NOTE); + if (pending.length > 0) parts.push(buildInboxContext(pending.map((m) => m.text))); + await out({ + hookSpecificOutput: { + hookEventName: "UserPromptSubmit", + additionalContext: parts.join("\n") + } + }); + if (soloNeeded) markSoloNotified(teamDir, Date.now(), "db"); + if (soloRetractNeeded) markSoloRetracted(teamDir); + if (pending.length > 0) { + writeReceipts(DATA, role.teamId, pending.map((m) => m.messageId), "userpromptsubmit"); + await boundedAck("mailbox.ack", { session_id: rawSessionId, messageIds: pending.map((m) => m.messageId) }); + } + } + } + } +} else if (event === "stop") { + if (role.role === "lead" && rawSessionId !== null) { + const teamDir = safeTeamDir(role.teamId); + if (teamDir !== null) { + recordLeadTurnEvent(teamDir, "stop"); + const pending = leadOff ? [] : await pendingForLead(teamDir, role.teamId); + if (pending.length > 0) { + const runKey = runKeyFor(input.stop_hook_active); + const budgetPaths = memberPaths(teamDir, role.teamId); + const state = readStopBudget(budgetPaths); + if (budgetAllows(state, runKey)) { + writeStopBudget(budgetPaths, nextBudget(state, runKey)); + await out({ + decision: "block", + reason: buildStopReason(pending.map((m) => m.text)) + }); + writeReceipts(DATA, role.teamId, pending.map((m) => m.messageId), "stop"); + await boundedAck("mailbox.ack", { session_id: rawSessionId, messageIds: pending.map((m) => m.messageId) }); + } + } + } + } +} +process.exitCode = 0; diff --git a/external_plugins/agent-team/runtime/ui/companion.js b/external_plugins/agent-team/runtime/ui/companion.js new file mode 100644 index 00000000..a7b9a55b --- /dev/null +++ b/external_plugins/agent-team/runtime/ui/companion.js @@ -0,0 +1,1092 @@ +"use strict"; +(() => { + // src/ui-core/tokens.ts + var TOKEN_CSS = ` +:root, [data-theme="light"] { + color-scheme: light; + /* \u6587\u5B57\u56DB\u6863\uFF08dsw label-primary/secondary/tertiary/caption\uFF1B + caption \u65E0\u72EC\u7ACB\u5BBF\u4E3B\u53D8\u91CF \u2192 tertiary \u540C\u6863 + \u5B57\u9762\u515C\u5E95\u533A\u5206\uFF09 */ + --at-label-primary: var(--color-text-primary, var(--foreground, #1a2233)); + --at-label-secondary: var(--color-text-secondary, var(--muted-foreground, #3d4a5c)); + --at-label-tertiary: var(--color-text-tertiary, var(--muted-foreground, #8a94a6)); + --at-label-caption: var(--color-text-tertiary, #9aa3b2); + /* \u80CC\u666F\u4E24\u6863\uFF08dsw specific-menu / bg-layer-2\uFF09 */ + --at-bg-menu: var(--color-background-secondary, var(--muted, #f7f8fa)); + --at-bg-layer-2: var(--color-background-primary, var(--card, #ffffff)); + /* \u63CF\u8FB9\u4E09\u6863\uFF08dsw border-l1/l2/l3\uFF1B\u5BBF\u4E3B\u5355\u6863 --border \u2192 \u4E09\u6863\u900F\u660E\u5EA6\u6D3E\u751F\uFF09 */ + --at-border-l1: var(--color-border-primary, var(--border, rgba(16, 24, 40, 0.08))); + --at-border-l2: var(--color-border-tertiary, var(--border, #e3e6eb)); + --at-border-l3: var(--color-border-secondary, var(--border, #c9cfd8)); + /* \u72B6\u6001\u70B9\u4E94\u7C7B\u8272\uFF08ongoing/idle/done/warning \u2192 --green/\u7070/--blue/--yellow \u6216\u81EA\u7ED8\uFF09 */ + --at-state-ongoing: var(--color-text-success, var(--green, #12a675)); + --at-state-error: var(--color-text-danger, var(--red, #e5484d)); + --at-state-idle: var(--color-text-disabled, #98a2b3); + --at-state-warning: var(--color-text-warning, var(--yellow, #f59e0b)); + --at-state-done: var(--color-text-info, var(--blue, #3e7bfa)); + /* \u4E1A\u52A1\u4E3B\u8272\uFF08dsw state-business-primary\uFF1A\u5F53\u524D\u4F1A\u8BDD\u9AD8\u4EAE/info Tag\uFF09 */ + --at-business: var(--color-text-info, var(--primary, #3e7bfa)); + /* \u9519\u8BEF\u6587\u672C\uFF08dsw state-error-primary\uFF09 */ + --at-error-text: var(--color-text-danger, var(--red, var(--destructive, #d93036))); + /* advisory \u8B66\u544A\u6587\u672C\u8272\uFF08\u6DF1\u7425\u73C0\u4FDD\u8BC1 11px \u5C0F\u5B57\u5BF9\u6BD4\u5EA6\uFF09 */ + --at-warning-text: var(--color-text-warning, var(--yellow, #b45309)); + /* \u9634\u5F71\u4E24\u6863\uFF08dsw elevation-prominent / elevation-panel\uFF09 */ + --at-shadow-prominent: var(--shadow-lg, 0 8px 28px rgba(16, 24, 40, 0.16)); + --at-shadow-panel: var(--shadow-md, 0 4px 16px rgba(16, 24, 40, 0.12)); + /* \u6EDA\u52A8\u6761\uFF08dsh scrollbar \u4EE4\u724C\u81EA\u7ED8\uFF09 */ + --at-scrollbar-thumb: color-mix(in srgb, var(--at-label-tertiary) 40%, transparent); + --at-scrollbar-thumb-hover: color-mix(in srgb, var(--at-label-tertiary) 60%, transparent); + /* \u5B57\u4F53\uFF08\u4E0D\u5F15\u5916\u90E8\u5B57\u4F53\uFF0C\u8DDF\u968F\u5BBF\u4E3B UI \u5B57\u4F53\u6808\uFF09 */ + --at-font: var(--font-sans, -apple-system, "PingFang SC", "Segoe UI", sans-serif); +} +[data-theme="dark"] { + color-scheme: dark; + --at-label-primary: var(--color-text-primary, var(--foreground, #e8eaf0)); + --at-label-secondary: var(--color-text-secondary, var(--muted-foreground, #c0c6d2)); + --at-label-tertiary: var(--color-text-tertiary, var(--muted-foreground, #8d95a3)); + --at-label-caption: var(--color-text-tertiary, #7d8593); + --at-bg-menu: var(--color-background-secondary, var(--muted, #1b1e24)); + --at-bg-layer-2: var(--color-background-primary, var(--card, #23262d)); + --at-border-l1: var(--color-border-primary, var(--border, rgba(255, 255, 255, 0.08))); + --at-border-l2: var(--color-border-tertiary, var(--border, #333842)); + --at-border-l3: var(--color-border-secondary, var(--border, #434a56)); + --at-state-ongoing: var(--color-text-success, var(--green, #2fbf8f)); + --at-state-error: var(--color-text-danger, var(--red, #ff6b6e)); + --at-state-idle: var(--color-text-disabled, #7d8593); + --at-state-warning: var(--color-text-warning, var(--yellow, #ffb454)); + --at-state-done: var(--color-text-info, var(--blue, #6c9cff)); + --at-business: var(--color-text-info, var(--primary, #6c9cff)); + --at-error-text: var(--color-text-danger, var(--red, var(--destructive, #ff8a8d))); + /* advisory \u8B66\u544A\u6587\u672C\u8272 */ + --at-warning-text: var(--color-text-warning, var(--yellow, #ffb454)); + --at-shadow-prominent: var(--shadow-lg, 0 8px 28px rgba(0, 0, 0, 0.5)); + --at-shadow-panel: var(--shadow-md, 0 4px 16px rgba(0, 0, 0, 0.4)); +} +`; + + // src/ui-core/css.ts + var COMPONENT_CSS = ` +${TOKEN_CSS} +* { box-sizing: border-box; } +.at-root { + font-family: var(--at-font); + font-size: 13px; + line-height: 1.5; + color: var(--at-label-primary); + width: 100%; +} +/* \xA710.3 \u9762\u677F\uFF1A\u5BBD min(500px, \u5BB9\u5668\u221232px)\uFF1B\u7D27\u51D1 min(320px,\u2026)\uFF1B\u6700\u5927\u9AD8 min(680px, \u89C6\u53E3\u221232px)\uFF1B + \u5706\u89D2 12\uFF1Bpadding 8px 2px 0\uFF1Bflex column\uFF1Boverflow hidden\uFF1Belevation-prominent \u9634\u5F71\uFF1B + border-l1 \u63CF\u8FB9\uFF08stroke \u7B49\u4EF7\uFF0C\u65E0 border\uFF09 */ +.team-panel { + width: min(500px, 100% - 32px); + max-height: min(680px, 100vh - 32px); + border-radius: 12px; + box-shadow: var(--at-shadow-prominent); + outline: 0.5px solid var(--at-border-l1); + background: var(--at-bg-menu); + padding: 8px 2px 0; + display: flex; + flex-direction: column; + overflow: hidden; + position: relative; +} +.team-panel.compact { width: min(320px, 100% - 32px); } +/* \xA710.3 body\uFF1Aoverflow-y auto\uFF1Bscrollbar-gutter stable\uFF1Bpadding 0 9px 16px 14px */ +.panel-body { + overflow-y: auto; + scrollbar-gutter: stable; + padding: 0 9px 16px 14px; + flex: auto; + min-height: 0; + scrollbar-color: var(--at-scrollbar-thumb) transparent; +} +.panel-body::-webkit-scrollbar { width: 8px; } +.panel-body::-webkit-scrollbar-thumb { + background: var(--at-scrollbar-thumb); + border-radius: 4px; +} +.panel-body::-webkit-scrollbar-thumb:hover { background: var(--at-scrollbar-thumb-hover); } +/* \xA710.5 \u8282\u6807\u9898\uFF1A13px/500\uFF0Cmargin 16px 0 8px 4px\uFF08\u9996\u8282 top 8px\uFF09\uFF0Cgap 8\uFF1B + count 12px/16px tabular-nums caption \u8272 */ +.panel-body h3 { + font-size: 13px; + font-weight: 500; + color: var(--at-label-primary); + margin: 16px 0 8px 4px; + display: flex; + align-items: center; + gap: 8px; +} +.panel-body section:first-of-type h3 { margin-top: 8px; } +h3 .count { + font-size: 12px; + line-height: 16px; + font-weight: 400; + color: var(--at-label-caption); + font-variant-numeric: tabular-nums; +} +/* \xA710.5 \u82B1\u540D\u518C\u7F51\u683C\uFF1A\u53CC\u5217 minmax(0,1fr) gap 8\uFF1B\u7D27\u51D1\u5355\u5217 */ +.roster { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } +.compact .roster { grid-template-columns: minmax(0, 1fr); } +/* \xA710.5 \u6210\u5458\u5361\uFF1A\u5706\u89D2 8\uFF1Bpadding 10px 12px\uFF1Bgap 8\uFF1Bbg-layer-2\uFF1B\u63CF\u8FB9 border-l2\uFF08stroke \u7B49\u4EF7\uFF09\uFF1B + \u6587\u5B57\u5DE6\u5BF9\u9F50\uFF1Bflex \u9876\u5BF9\u9F50\uFF1Bhover\uFF08\u975E\u7981\u7528\uFF09border-l3 + elevation-panel\uFF1Bdisabled cursor default */ +.member { + border-radius: 8px; + padding: 10px 12px; + gap: 8px; + background: var(--at-bg-layer-2); + box-shadow: 0 0 0 0.5px var(--at-border-l2); + border: none; + text-align: left; + display: flex; + align-items: flex-start; + font: inherit; + color: inherit; + min-width: 0; + cursor: pointer; +} +.member:disabled { cursor: default; } +.member:not(:disabled):hover, +.member:not(:disabled):focus-visible { + box-shadow: 0 0 0 0.5px var(--at-border-l3), var(--at-shadow-panel); +} +/* \u5F53\u524D\u4F1A\u8BDD\u9AD8\u4EAE\uFF08\u4EC5 members>1\uFF09\uFF1Abusiness 40% \u6DF7\u8272\u63CF\u8FB9 + inset 1px \u5185\u73AF */ +.member.current { + box-shadow: 0 0 0 0.5px color-mix(in srgb, var(--at-business) 40%, transparent), + inset 0 0 0 1px color-mix(in srgb, var(--at-business) 40%, transparent); +} +/* \u540D\u5B57/\u6B21\u884C\u6587\u672C\u5217\uFF08\xA710.5 memberText\uFF1Acolumn\uFF0Cmin-width 0 \u4F9B ellipsis\uFF09 */ +.member .member-text { display: flex; flex-direction: column; min-width: 0; gap: 2px; } +.member .row1 { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 100%; } +/* \u72B6\u6001\u70B9\u5BB9\u5668\uFF1A1lh \u9AD8\u5782\u76F4\u5BF9\u9F50\uFF08\xA710.5 memberDot\uFF09 */ +.member-dot { flex: none; align-items: center; height: 1lh; display: inline-flex; } +.member .name { + font-weight: 500; + color: var(--at-label-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; +} +.member .sub { + font-size: 11px; + color: var(--at-label-tertiary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100%; +} +/* hover/focus \u624D\u663E\u793A\u300C \xB7 \u6A21\u578B: model\u300D\uFF08\xA710.5/V06\uFF09 */ +.member .model { display: none; } +.member:hover .model, +.member:focus-visible .model { display: inline; } +.member .diagnostic { + font-size: 11px; + color: var(--at-error-text); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100%; +} +/* \u5F53\u524D\u4F1A\u8BDD Tag\uFF0810px/15px\uFF0Cpadding 0 4px\uFF0Cinfo tone\uFF09 */ +.current-tag { + font-size: 10px; + line-height: 15px; + padding: 0 4px; + border-radius: 4px; + background: color-mix(in srgb, var(--at-business) 16%, transparent); + color: var(--at-business); + flex: none; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +/* 0.4.0 \u6CE8\u9500\u6210\u5458\u5361/\u9F7F\u8F6E\u4E0E\u8BBE\u7F6E\u5F39\u7A97\u6837\u5F0F\uFF08member-card\u3001member-gear\u3001settings \u7CFB\u5217\u3001 + source-badge\u3001modal-select\uFF09\uFF1A\u6210\u5458\u6A21\u578B\u552F\u4E00\u8DEF\u7EBF = \u6BCF\u8F6E\u8DDF\u968F Lead\uFF0C\u9762\u677F\u6062\u590D\u96F6\u53D8\u66F4\u901A\u9053\u3002 */ +/* \u72B6\u6001\u70B9\uFF1A\u76F4\u5F84\u4E00\u81F4 8px\uFF08V06\uFF09 */ +.dot { width: 8px; height: 8px; border-radius: 50%; flex: none; display: inline-block; } +.dot.ongoing { background: var(--at-state-ongoing); } +.dot.error { background: var(--at-state-error); } +.dot.idle { background: var(--at-state-idle); } +.dot.warning { background: var(--at-state-warning); } +.dot.done { background: var(--at-state-done); } +/* inactive \u4EBA\u5F62\u56FE\u6807\uFF1A14px tertiary\uFF08\xA710.5/V06\uFF09 */ +.icon-user { width: 14px; height: 14px; flex: none; color: var(--at-label-tertiary); display: inline-flex; } +/* \xA710.4 \u901A\u77E5\u6761\uFF1Aflex gap 6 padding 9 \u5B57\u53F7 12\uFF1Berror = \u9519\u8BEF\u8272\uFF1B\u6309\u5E8F\u6E32\u67D3 */ +.notice, .error-bar { + display: flex; + align-items: center; + gap: 6px; + padding: 9px; + font-size: 12px; +} +.error-bar { color: var(--at-error-text); } +.notice { color: var(--at-label-secondary); } +/* \xA710.6 \u4EFB\u52A1\u677F\uFF1A\u7A7A\u677F\u6BB5\u843D 12px tertiary margin 16px 0 0 4px\uFF1B\u5217\u8868 flex column gap 7 */ +.empty-notice { font-size: 12px; color: var(--at-label-tertiary); margin: 16px 0 0 4px; } +.tasks { display: flex; flex-direction: column; gap: 7px; } +/* \u4EFB\u52A1\u5361\uFF1Aborder 0.5px border-l2\uFF1B\u5706\u89D2 9\uFF1Bpadding 11px 13px\uFF1Bbg-layer-2 */ +article.task { + border: 0.5px solid var(--at-border-l2); + border-radius: 9px; + padding: 11px 13px; + background: var(--at-bg-layer-2); +} +.task .title-row { display: flex; align-items: center; gap: 8px; } +.task strong { font-size: 13px; font-weight: 500; line-height: 1.4; color: var(--at-label-primary); } +/* \u72B6\u6001\u5FBD\u6807\u53F3\u5BF9\u9F50 11px gap 6 */ +.task .task-state { + margin-left: auto; + font-size: 11px; + color: var(--at-label-tertiary); + display: inline-flex; + align-items: center; + gap: 6px; + flex: none; +} +/* \u63CF\u8FF0 12px/18px pre-wrap margin 5px 0\uFF1B\u4E24\u884C\u622A\u65AD */ +.task p { + font-size: 12px; + line-height: 18px; + color: var(--at-label-secondary); + white-space: pre-wrap; + margin: 5px 0; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} +.task p.expanded { -webkit-line-clamp: unset; display: block; } +/* \u5C55\u5F00\u5F00\u5173\uFF1Afloat right\uFF1B11px/20px\uFF1Bchevron 12px \u65CB\u8F6C 180\xB0 transition .12s */ +.expand-toggle { + float: right; + font-size: 11px; + line-height: 20px; + color: var(--at-label-tertiary); + background: none; + border: none; + cursor: pointer; + padding: 0; + margin-left: 10px; + font-family: inherit; + display: inline-flex; + align-items: center; + gap: 2px; +} +.expand-toggle:hover, .expand-toggle:focus-visible { color: var(--at-label-primary); } +.expand-toggle svg { transition: transform 0.12s; } +.expand-toggle.open svg { transform: rotate(180deg); } +.expand-toggle[hidden] { display: none; } +/* meta \u884C\uFF1A11px/20px\uFF1B\u5B50\u9879\u95F4\u8DDD 10px\uFF1Bwarning \u63D0\u9192\u8272\uFF08advisory \u975E\u9519\u8BEF\uFF09 */ +.task .meta { font-size: 11px; line-height: 20px; color: var(--at-label-tertiary); } +.task .meta > span { margin-right: 10px; } +.task .meta .warning { color: var(--at-warning-text); } +/* T5.7 \u6210\u5458\u4F1A\u8BDD\u67E5\u770B\u89C6\u56FE\uFF08V16\uFF1A\u65E0 DSH \u53C2\u7167\uFF0C\u5BBF\u4E3B\u98CE\u683C\uFF1B\u5224\u636E=\u4E0D\u7834\u7248+\u51E0\u4F55\u4E00\u81F4\uFF09 */ +.detail-view { display: flex; flex-direction: column; min-height: 0; flex: auto; } +.detail-head { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 9px 8px 6px; + border-bottom: 0.5px solid var(--at-border-l2); + flex: none; +} +.detail-back { + display: inline-flex; + align-items: center; + gap: 4px; + background: none; + border: none; + color: var(--at-label-tertiary); + font: inherit; + font-size: 12px; + cursor: pointer; + padding: 2px 6px; + border-radius: 6px; +} +.detail-back:hover, .detail-back:focus-visible { color: var(--at-label-primary); background: color-mix(in srgb, var(--at-label-tertiary) 10%, transparent); } +.detail-title { font-size: 13px; font-weight: 500; color: var(--at-label-primary); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.detail-actions { margin-left: auto; display: inline-flex; gap: 6px; flex: none; } +.detail-action { + background: none; + border: 0.5px solid var(--at-border-l2); + border-radius: 6px; + color: var(--at-label-secondary); + font: inherit; + font-size: 11px; + line-height: 18px; + padding: 1px 8px; + cursor: pointer; +} +.detail-action:hover, .detail-action:focus-visible { color: var(--at-label-primary); border-color: var(--at-border-l3); } +.detail-list { overflow-y: auto; scrollbar-gutter: stable; padding: 8px 9px 16px 14px; flex: auto; min-height: 0; scrollbar-color: var(--at-scrollbar-thumb) transparent; } +.detail-state { font-size: 12px; color: var(--at-label-tertiary); padding: 16px 4px; display: flex; align-items: center; gap: 6px; } +.detail-state.error { color: var(--at-error-text); } +.msg { margin: 0 0 10px; min-width: 0; } +.msg-head { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--at-label-tertiary); margin-bottom: 2px; } +.msg-role { font-weight: 500; color: var(--at-label-secondary); } +.msg-time { font-variant-numeric: tabular-nums; } +.msg-text { + font-size: 12px; + line-height: 18px; + color: var(--at-label-primary); + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; +} +.msg.user .msg-text { color: var(--at-label-secondary); } +.msg-badge { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: 10px; + line-height: 15px; + padding: 0 4px; + border-radius: 4px; + background: color-mix(in srgb, var(--at-business) 16%, transparent); + color: var(--at-business); +} +.msg-badge.hook { background: color-mix(in srgb, var(--at-label-tertiary) 14%, transparent); color: var(--at-label-tertiary); } +.tool-row { display: block; width: 100%; text-align: left; background: none; border: none; border-top: 0.5px solid var(--at-border-l2); padding: 4px 0; margin-top: 4px; font: inherit; cursor: pointer; color: var(--at-label-tertiary); } +.tool-row:hover, .tool-row:focus-visible { color: var(--at-label-primary); } +.tool-static { display: block; border-top: 0.5px solid var(--at-border-l2); padding: 4px 0; margin-top: 4px; color: var(--at-label-tertiary); } +.tool-row .tool-summary, .tool-static .tool-summary { display: inline-flex; align-items: center; gap: 6px; font-size: 11px; line-height: 20px; } +.tool-row .tool-name, .tool-static .tool-name { font-weight: 500; color: var(--at-label-secondary); } +.tool-row svg { transition: transform 0.12s; } +.tool-row.open svg { transform: rotate(180deg); } +.tool-detail { + display: none; + font-size: 11px; + line-height: 16px; + color: var(--at-label-tertiary); + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; + max-height: 200px; + overflow-y: auto; + margin: 2px 0 0 18px; +} +.tool-row.open + .tool-detail { display: block; } +/* toolGroup\uFF1A\u6309\u8F6E\u52A8\u4F5C\u7EC4\uFF08\u5934\u90E8\u4E00\u884C\u6C47\u603B\uFF1B\u5C55\u5F00\u9010\u6761\u5DE5\u5177\u884C\uFF0C\u7F29\u8FDB\u5BF9\u9F50 tool-detail\uFF09 */ +.tool-group-head { + display: flex; + align-items: center; + gap: 6px; + width: 100%; + text-align: left; + background: none; + border: none; + border-top: 0.5px solid var(--at-border-l2); + padding: 4px 0; + margin-top: 4px; + font: inherit; + color: var(--at-label-tertiary); + cursor: pointer; +} +.tool-group-head:hover, .tool-group-head:focus-visible { color: var(--at-label-primary); } +.tool-group-head .tool-group-label { font-size: 11px; line-height: 20px; color: var(--at-label-secondary); } +.tool-group-head:hover .tool-group-label, +.tool-group-head:focus-visible .tool-group-label { color: var(--at-label-primary); } +.tool-group-head svg { flex: none; transition: transform 0.12s; } +.tool-group.open .tool-group-head svg { transform: rotate(180deg); } +.tool-group-items { display: none; margin-left: 18px; } +.tool-group.open .tool-group-items { display: block; } +.tool-group-items > :first-child { border-top: none; } +.detail-pager { display: flex; align-items: center; gap: 8px; padding: 4px 0 8px; } +.detail-pager .detail-action[disabled] { opacity: 0.45; cursor: default; } +`; + + // src/ui-core/dict.ts + var DICT = { + zh: { + trigger: "\u667A\u80FD\u4F53\u56E2\u961F", + loading: "\u6B63\u5728\u52A0\u8F7D\u56E2\u961F\u2026", + unavailable: "Team \u6682\u4E0D\u53EF\u7528", + failure: "\u56E2\u961F\u6301\u4E45\u8BB0\u5F55\u65E0\u6548\uFF1A{message}", + empty: "\u6682\u65E0\u5171\u4EAB\u4EFB\u52A1\uFF0C\u53EF\u4EE5\u901A\u8FC7\u5BF9\u8BDD\u521B\u5EFA", + roster: "\u6210\u5458", + tasks: "\u5171\u4EAB\u4EFB\u52A1", + model: "\u6A21\u578B", + open: "\u6253\u5F00\u6210\u5458\u4F1A\u8BDD", + current: "\u5F53\u524D\u4F1A\u8BDD", + owner: "Owner", + unowned: "\u672A\u5206\u914D", + blockedBy: "\u4F9D\u8D56", + writeScopes: "\u5199\u5165\u8303\u56F4", + ready: "\u53EF\u5F00\u59CB", + blocked: "\u88AB\u4F9D\u8D56\u963B\u585E", + "task.expand": "\u5C55\u5F00", + "task.collapse": "\u6536\u8D77", + "memberStatus.running": "\u8FD0\u884C\u4E2D", + "memberStatus.inactive": "\u672A\u8FD0\u884C", + "memberStatus.provisioning": "\u51C6\u5907\u4E2D", + "memberStatus.failed": "\u5931\u8D25", + "status.pending": "\u5F85\u5904\u7406", + "status.in_progress": "\u8FDB\u884C\u4E2D", + "status.completed": "\u5DF2\u5B8C\u6210" + }, + en: { + trigger: "Agent Team", + loading: "Loading Team\u2026", + unavailable: "Team is unavailable", + failure: "Invalid persisted Team record: {message}", + empty: "No shared tasks yet. Create them through the conversation.", + roster: "Members", + tasks: "Shared tasks", + model: "Model", + open: "Open member conversation", + current: "Current chat", + owner: "Owner", + unowned: "Unowned", + blockedBy: "Blocked by", + writeScopes: "Write scopes", + ready: "Ready", + blocked: "Blocked by dependencies", + "task.expand": "Show more", + "task.collapse": "Show less", + "memberStatus.running": "Running", + "memberStatus.inactive": "Inactive", + "memberStatus.provisioning": "Provisioning", + "memberStatus.failed": "Failed", + "status.pending": "Pending", + "status.in_progress": "In progress", + "status.completed": "Completed" + } + }; + var DETAIL_DICT = { + zh: { + "detail.back": "\u8FD4\u56DE", + "detail.title": "\u6210\u5458\u4F1A\u8BDD", + "detail.loading": "\u6B63\u5728\u52A0\u8F7D\u4F1A\u8BDD\u2026", + "detail.empty": "\u8BE5\u6210\u5458\u6682\u65E0\u4F1A\u8BDD\u6D88\u606F", + "detail.failed": "\u4F1A\u8BDD\u8BFB\u53D6\u5931\u8D25\uFF1A{message}", + "detail.refresh": "\u5237\u65B0", + "detail.copySessionId": "\u590D\u5236\u4F1A\u8BDD id", + "detail.copied": "\u5DF2\u590D\u5236", + "detail.earlier": "\u66F4\u65E9\u6D88\u606F", + "detail.wake": "\u8BF7\u6C42 Lead \u5524\u9192\u8BE5\u6210\u5458", + "detail.wakeInjected": "\u5DF2\u6CE8\u5165\u4E0B\u4E00\u8F6E\uFF1A\u8BF7\u6C42\u5524\u9192 {name}", + "detail.framedFrom": "Team \u6D88\u606F \xB7 \u6765\u81EA {name}", + "detail.hookBadge": "hook \u6CE8\u5165", + "detail.toolCall": "\u5DE5\u5177\u8C03\u7528", + "detail.noSession": "\u4F1A\u8BDD id \u672A\u843D\u5B9A\uFF08\u6210\u5458\u53EF\u80FD\u5C1A\u5728\u51C6\u5907\u4E2D\uFF09", + "detail.you": "\u6211", + "detail.count": "{n} \u6761", + "detail.toolGroup": "{n} \u4E2A\u52A8\u4F5C \xB7 {list}", + "detail.countSummary": "{n} \u6761 \xB7 \u5171 {sourceTotal} \u6761\u8F6C\u5F55" + }, + en: { + "detail.back": "Back", + "detail.title": "Member conversation", + "detail.loading": "Loading conversation\u2026", + "detail.empty": "No conversation messages for this member yet", + "detail.failed": "Conversation read failed: {message}", + "detail.refresh": "Refresh", + "detail.copySessionId": "Copy session id", + "detail.copied": "Copied", + "detail.earlier": "Earlier messages", + "detail.wake": "Ask Lead to wake this member", + "detail.wakeInjected": "Injected for next turn: wake request for {name}", + "detail.framedFrom": "Team message \xB7 from {name}", + "detail.hookBadge": "hook injected", + "detail.toolCall": "Tool call", + "detail.noSession": "Session id not settled yet (member may still be provisioning)", + "detail.you": "me", + "detail.count": "{n} items", + "detail.toolGroup": "{n} actions \xB7 {list}", + "detail.countSummary": "{n} items \xB7 of {sourceTotal} transcript items" + } + }; + function t(lang2, key, vars) { + return interpolate(DICT[lang2][key], vars); + } + function td(lang2, key, vars) { + return interpolate(DETAIL_DICT[lang2][key], vars); + } + function interpolate(template, vars) { + if (vars === void 0) return template; + return template.replace( + /\{(\w+)\}/g, + (m, k) => k in vars ? String(vars[k]) : m + ); + } + function langOfLocale(locale) { + return typeof locale === "string" && locale.toLowerCase().startsWith("zh") ? "zh" : "en"; + } + function statusKey(status) { + return status === "deleted" ? "status.completed" : `status.${status}`; + } + function memberStatusKey(status) { + return `memberStatus.${status}`; + } + + // src/ui-core/icons.ts + var svg = (inner, size) => ``; + function iconUser(size = 14) { + return svg('', size); + } + function iconUsers(size = 14) { + return svg( + '', + size + ); + } + function iconChevron(size = 12) { + return svg('', size); + } + function iconArrowLeft(size = 14) { + return svg('', size); + } + + // src/ui-core/escape.ts + function esc(s) { + return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); + } + + // src/ui-core/render.ts + function isCompact(frame2) { + return frame2.members.length === 1 && frame2.tasks.length === 0; + } + function currentMemberId(frame2) { + const sid = frame2.meta.sessionId; + if (sid === void 0) return void 0; + return frame2.members.find((m) => m.sessionId === sid)?.id; + } + function isMemberDisabled(m, currentId) { + return m.id === currentId || m.status === "failed" || m.status === "provisioning"; + } + function memberDot(status) { + switch (status) { + case "running": + case "provisioning": + return "ongoing"; + case "failed": + return "error"; + case "inactive": + default: + return "icon"; + } + } + function taskDot(task) { + switch (task.status) { + case "in_progress": + return "ongoing"; + case "completed": + return "done"; + case "deleted": + return "idle"; + // 上游 deleted→idle(视图通常不含墓碑,防御口径) + case "pending": + default: + return task.ready ? "idle" : "warning"; + } + } + function dot(state) { + return ``; + } + function memberIndicator(m) { + const d = memberDot(m.status); + const inner = d === "icon" ? `${iconUser(14)}` : dot(d); + return `${inner}`; + } + function renderMember(m, opts) { + const { lang: lang2, isCurrent, disabled } = opts; + const highlight = opts.highlightCurrent ?? isCurrent; + const cls = ["member", highlight ? "current" : ""].filter(Boolean).join(" "); + const nameRow = `${esc(m.target)}` + (isCurrent ? `${esc(t(lang2, "current"))}` : "") + ``; + const modelSuffix = m.model !== void 0 ? ` \xB7 ${esc(t(lang2, "model"))}: ${esc(m.model)}` : ""; + const sub = `${esc(t(lang2, memberStatusKey(m.status)))}${modelSuffix}`; + const diag = m.diagnostics.length > 0 ? `${esc(m.diagnostics[0])}` : ""; + const openAttr = disabled ? "" : ` title="${esc(t(lang2, "open"))}"`; + return ``; + } + function renderRoster(frame2, lang2) { + const members = frame2.members; + const currentId = currentMemberId(frame2); + const countHtml = members.length > 1 ? `${members.length}` : ""; + const cards = members.map( + (m) => renderMember(m, { + lang: lang2, + // Tag 恒随当前会话;高亮/描边才受 members>1 限制(上游 TeamAction 同口径)。 + isCurrent: m.id === currentId, + highlightCurrent: m.id === currentId && members.length > 1, + disabled: isMemberDisabled(m, currentId) + }) + ).join(""); + return `

${esc(t(lang2, "roster"))}${countHtml}

${cards}
`; + } + function renderTaskMeta(task, lang2, leadingHtml = "") { + const spans = []; + spans.push(`${esc(task.id)}`); + const owner = task.ownerName !== void 0 ? esc(task.ownerName) : esc(t(lang2, "unowned")); + spans.push(`${esc(t(lang2, "owner"))}: ${owner}`); + if (task.status === "pending") { + spans.push(`${esc(t(lang2, task.ready ? "ready" : "blocked"))}`); + } + if (task.blockedBy.length > 0) { + spans.push(`${esc(t(lang2, "blockedBy"))}: ${task.blockedBy.map(esc).join(", ")}`); + } + if (task.writeScopes.length > 0) { + spans.push(`${esc(t(lang2, "writeScopes"))}: ${task.writeScopes.map(esc).join(", ")}`); + } + for (const w of task.writeScopeWarnings) { + spans.push(`${esc(w)}`); + } + return `
${leadingHtml}${spans.join("")}
`; + } + function renderTask(task, lang2) { + const state = `${dot(taskDot(task))}${esc(t(lang2, statusKey(task.status)))}`; + const titleRow = `
${esc(task.subject)}${state}
`; + const toggle = ``; + const desc = `

${esc(task.description)}

`; + return `
` + titleRow + desc + renderTaskMeta(task, lang2, toggle) + `
`; + } + function renderTasks(frame2, lang2) { + if (frame2.tasks.length === 0) { + return `

${esc(t(lang2, "empty"))}

`; + } + const cards = frame2.tasks.map((task) => renderTask(task, lang2)).join(""); + return `

${esc(t(lang2, "tasks"))}${frame2.tasks.length}

${cards}
`; + } + function renderNotices(opts) { + const { lang: lang2 } = opts; + const out = []; + if (opts.navError !== void 0) { + out.push(``); + } + if (opts.loading === true) { + out.push(`
${dot("ongoing")}${esc(t(lang2, "loading"))}
`); + } else if (opts.noTeam === true) { + out.push(`
${dot("warning")}${esc(t(lang2, "unavailable"))}
`); + } + if (opts.failure !== void 0) { + out.push(``); + } + return out.join(""); + } + function renderPanelBody(frame2, lang2, runtime) { + const noTeam = frame2.team === null; + const notices = renderNotices({ + lang: lang2, + ...runtime?.navError !== void 0 ? { navError: runtime.navError } : {}, + ...runtime?.loading !== void 0 ? { loading: runtime.loading } : {}, + noTeam, + ...frame2.team?.failure !== void 0 ? { failure: frame2.team.failure } : {} + }); + if (noTeam && runtime?.loading !== true) { + return notices; + } + return notices + renderRoster(frame2, lang2) + renderTasks(frame2, lang2); + } + + // src/ui-core/detail-render.ts + function aggregateToolNames(tools) { + const counts = /* @__PURE__ */ new Map(); + for (const tool of tools) counts.set(tool.name, (counts.get(tool.name) ?? 0) + 1); + return [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([name, n]) => `${name}\xD7${n}`).join(" \xB7 "); + } + function renderToolEntry(tool) { + const hasPayload = tool.text !== void 0 && tool.text.length > 0; + const summary = `${hasPayload ? iconChevron(12) : ""}${esc(tool.name)}${esc(tool.status)}`; + return hasPayload ? `
${esc(tool.text)}
` : `${summary}`; + } + function renderDetailItem(item, lang2) { + const time = item.ts.slice(11, 19); + const badge = item.framed !== void 0 ? `${esc(td(lang2, "detail.framedFrom", { name: item.framed.from }))}` : ""; + if (item.kind === "toolCall") { + const tool = item.tool ?? { name: "?", status: "?" }; + const entry = { + ts: item.ts, + name: tool.name, + status: tool.status, + ...item.text !== void 0 ? { text: item.text } : {} + }; + return `
assistant${time}
` + renderToolEntry(entry) + `
`; + } + if (item.kind === "toolGroup") { + const tools = item.tools ?? []; + const count = item.count ?? tools.length; + const label = td(lang2, "detail.toolGroup", { n: count, list: aggregateToolNames(tools) }); + return `
assistant${time}
${tools.map((tool) => renderToolEntry(tool)).join("")}
`; + } + const roleLabel = item.role === "user" ? esc(td(lang2, "detail.you")) : item.role; + return `
${roleLabel}${time}${badge}
${esc(item.text ?? "")}
`; + } + function renderDetailBody(st, lang2) { + if (st.kind === "loading") { + return `
${esc(td(lang2, "detail.loading"))}
`; + } + if (st.kind === "error") { + const text = st.reason === "session-not-settled" ? td(lang2, "detail.noSession") : td(lang2, "detail.failed", { message: st.message }); + return `
${esc(text)}
`; + } + const d = st.detail; + const count = `${esc(td(lang2, "detail.countSummary", { n: d.total, sourceTotal: d.sourceTotal }))}`; + if (d.page.items.length === 0) { + return `
${esc(td(lang2, "detail.empty"))}
`; + } + const pager = d.page.nextCursor !== void 0 ? `
${count}
` : `
${count}
`; + return pager + d.page.items.map((item) => renderDetailItem(item, lang2)).join(""); + } + function renderDetailView(st, lang2, opts = {}) { + if (st.kind === "closed") return ""; + const actions = []; + if (st.kind === "ready") { + actions.push(``); + actions.push( + `` + ); + if (opts.wake === true) { + actions.push(``); + } + } + return `
${esc(st.name)}${actions.join("")}
${renderDetailBody(st, lang2)}
`; + } + + // src/ui-core/expand.ts + function memoryExpandStore(initial) { + const set = new Set(initial ?? []); + return { + isExpanded: (id) => set.has(id), + setExpanded: (id, v) => { + if (v) set.add(id); + else set.delete(id); + } + }; + } + function attachExpandBehavior(root2, store, labels) { + const observers = []; + const measure = (task) => { + const desc = task.querySelector("[data-task-desc]"); + const toggle = task.querySelector("[data-task-toggle]"); + if (desc === null || toggle === null) return; + const id = task.dataset.taskId ?? ""; + const expanded = store.isExpanded(id); + const overflow = desc.scrollHeight > desc.clientHeight + 1; + toggle.hidden = !(overflow || expanded); + const label = toggle.querySelector(".expand-label"); + if (label !== null) label.textContent = expanded ? labels.collapse : labels.expand; + toggle.setAttribute("aria-expanded", expanded ? "true" : "false"); + toggle.classList.toggle("open", expanded); + desc.classList.toggle("expanded", expanded); + }; + const tasks = () => Array.from(root2.querySelectorAll("article.task")); + for (const task of tasks()) { + const desc = task.querySelector("[data-task-desc]"); + if (desc !== null && typeof ResizeObserver !== "undefined") { + const ro = new ResizeObserver(() => measure(task)); + ro.observe(desc); + observers.push(ro); + } + measure(task); + } + const onClick = (ev) => { + const target = ev.target; + const toggle = target?.closest("[data-task-toggle]"); + if (toggle === null || toggle === void 0) return; + const task = toggle.closest("article.task"); + if (task === null) return; + const id = task.dataset.taskId ?? ""; + store.setExpanded(id, !store.isExpanded(id)); + measure(task); + }; + root2.addEventListener("click", onClick); + return () => { + root2.removeEventListener("click", onClick); + for (const ro of observers) ro.disconnect(); + }; + } + + // src/ui-core/request-sequencer.ts + var RequestSequencer = class { + #seq = 0; + begin() { + this.#seq += 1; + return this.#seq; + } + isCurrent(seq) { + return seq === this.#seq; + } + invalidate() { + this.#seq += 1; + } + }; + + // src/panel/companion-main.ts + var HOVER_OPEN_MS = 150; + var LEAVE_CLOSE_MS = 120; + var ANCHOR_GAP = 5; + var ANCHOR_MARGIN = 16; + var EVENTS_ENDPOINT = "/events"; + var API_ENDPOINT = "/api/call"; + var token = new URLSearchParams(location.search).get("token") ?? ""; + var lang = langOfLocale(navigator.language); + var frame = null; + var detailState = { kind: "closed" }; + var expandStore = memoryExpandStore(); + var detachExpand = null; + var pinned = false; + var open = false; + var hoverTimer = null; + var leaveTimer = null; + var detailSequencer = new RequestSequencer(); + var style = document.createElement("style"); + style.textContent = COMPONENT_CSS + ` +html, body { margin: 0; min-height: 100%; background: var(--at-bg-menu); font-family: var(--at-font); } +.at-root { padding: 12px; container-type: inline-size; } +.at-trigger { + min-height: 28px; color: var(--at-label-tertiary); cursor: pointer; background: none; border: 0; + border-radius: 6px; align-items: center; gap: 5px; padding: 3px 7px; font-size: 12px; + display: inline-flex; font-family: inherit; +} +.at-trigger:hover, .at-trigger:focus-visible { color: var(--at-label-primary); } +.at-trigger .at-trigger-label { display: inline; } +@container (max-width: 480px) { .at-trigger .at-trigger-label { display: none; } } +.at-panel-wrap { position: fixed; visibility: hidden; left: 0; top: 0; z-index: 100; } +.at-panel-wrap.open { visibility: visible; } +.team-panel { position: relative; } +.at-conn { font-size: 11px; color: var(--at-label-tertiary); margin-left: 8px; } +`; + document.head.appendChild(style); + var root = document.createElement("div"); + root.className = "at-root"; + root.innerHTML = `connecting\u2026
`; + document.body.appendChild(root); + var trigger = root.querySelector("[data-trigger]"); + trigger.querySelector("[data-trigger-icon]").innerHTML = iconUsers(14); + var wrap = root.querySelector("[data-wrap]"); + var panelEl = root.querySelector(".team-panel"); + var listView = root.querySelector("[data-list-view]"); + var detailView = root.querySelector("[data-detail-view]"); + var conn = root.querySelector("[data-conn]"); + document.documentElement.dataset.theme = matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; + function render() { + const inDetail = detailState.kind !== "closed"; + listView.hidden = inDetail; + detailView.hidden = !inDetail; + panelEl.classList.toggle("compact", frame !== null && isCompact(frame) && !inDetail); + if (inDetail) { + detailView.innerHTML = renderDetailView(detailState, lang); + bindDetail(); + return; + } + if (detachExpand !== null) { + detachExpand(); + detachExpand = null; + } + if (frame === null) { + listView.innerHTML = renderPanelBody( + { type: "view", stateVersion: 4, team: null, members: [], tasks: [], meta: { generatedAt: "", revision: 0 } }, + lang, + { loading: true } + ); + return; + } + listView.innerHTML = renderPanelBody(frame, lang, { loading: false }); + detachExpand = attachExpandBehavior(listView, expandStore, { + expand: DICT[lang]["task.expand"], + collapse: DICT[lang]["task.collapse"] + }); + } + function positionPanel() { + const tr = trigger.getBoundingClientRect(); + const pw = panelEl.offsetWidth; + const ph = panelEl.offsetHeight; + let left = tr.left; + let top = tr.bottom + ANCHOR_GAP; + const maxLeft = window.innerWidth - pw - ANCHOR_MARGIN; + if (left > maxLeft) left = Math.max(ANCHOR_MARGIN, maxLeft); + if (top + ph > window.innerHeight - ANCHOR_MARGIN) { + const above = tr.top - ANCHOR_GAP - ph; + if (above >= ANCHOR_MARGIN) top = above; + } + wrap.style.left = `${Math.round(left)}px`; + wrap.style.top = `${Math.round(top)}px`; + } + function openPanel(focus) { + if (open) return; + open = true; + wrap.classList.add("open"); + trigger.setAttribute("aria-expanded", "true"); + positionPanel(); + if (focus) panelEl.focus(); + } + function closePanel(returnFocus) { + if (!open) return; + open = false; + pinned = false; + wrap.classList.remove("open"); + trigger.setAttribute("aria-expanded", "false"); + if (returnFocus) trigger.focus(); + } + var triggerLabel = root.querySelector(".at-trigger-label"); + trigger.addEventListener("mouseenter", () => { + if (pinned) return; + if (triggerLabel !== null && getComputedStyle(triggerLabel).display === "none") return; + clearTimers(); + hoverTimer = setTimeout(() => openPanel(false), HOVER_OPEN_MS); + }); + trigger.addEventListener("mouseleave", () => { + if (pinned) return; + clearTimers(); + leaveTimer = setTimeout(() => closePanel(false), LEAVE_CLOSE_MS); + }); + panelEl.addEventListener("mouseenter", () => { + if (leaveTimer !== null) { + clearTimeout(leaveTimer); + leaveTimer = null; + } + }); + panelEl.addEventListener("mouseleave", () => { + if (pinned || !open) return; + clearTimers(); + leaveTimer = setTimeout(() => closePanel(false), LEAVE_CLOSE_MS); + }); + trigger.addEventListener("click", () => { + clearTimers(); + pinned = true; + if (open) panelEl.focus(); + else openPanel(true); + }); + document.addEventListener("keydown", (ev) => { + if (ev.key !== "Escape") return; + const inPanel = panelEl.contains(document.activeElement) || document.activeElement === panelEl; + if (open) { + ev.preventDefault(); + closePanel(inPanel); + } + }); + document.addEventListener("pointerdown", (ev) => { + if (!open) return; + const t2 = ev.target; + if (trigger.contains(t2) || panelEl.contains(t2)) return; + closePanel(false); + }); + window.addEventListener("resize", () => { + if (open) positionPanel(); + }); + window.addEventListener("scroll", () => { + if (open) positionPanel(); + }, true); + function clearTimers() { + if (hoverTimer !== null) { + clearTimeout(hoverTimer); + hoverTimer = null; + } + if (leaveTimer !== null) { + clearTimeout(leaveTimer); + leaveTimer = null; + } + } + function connect() { + const es = new EventSource(`${EVENTS_ENDPOINT}?token=${encodeURIComponent(token)}`); + es.addEventListener("hello", () => { + conn.textContent = "live"; + }); + es.addEventListener("view", (ev) => { + try { + frame = JSON.parse(ev.data); + conn.textContent = "live"; + render(); + } catch { + } + }); + es.onerror = () => { + conn.textContent = "reconnecting\u2026"; + }; + } + async function apiCall(args) { + const res = await fetch(API_ENDPOINT, { + method: "POST", + headers: { "content-type": "application/json", "x-team-token": token }, + body: JSON.stringify(args) + }); + return res.json(); + } + listView.addEventListener("click", (ev) => { + const target = ev.target; + if (target?.closest("[data-task-toggle]") !== null && target !== void 0) return; + const member = target?.closest("button.member"); + if (member === null || member === void 0 || member.disabled) return; + const id = member.dataset.memberId; + if (id === void 0) return; + void openDetail(id, member.querySelector(".name")?.textContent ?? id); + }); + async function openDetail(memberId, name, cursor) { + const seq = detailSequencer.begin(); + const fromList = detailState.kind === "closed"; + detailState = { kind: "loading", memberId, name }; + render(); + if (fromList) detailView.focus(); + try { + const body = await apiCall({ + action: "detail", + target: memberId, + ...cursor !== void 0 ? { cursor } : {} + }); + if (!detailSequencer.isCurrent(seq)) return; + if (body.kind === "detail" && body.detail !== void 0) { + detailState = { kind: "ready", memberId, name, detail: body.detail }; + } else { + detailState = { + kind: "error", + memberId, + name, + message: body.message ?? "detail failed", + ...body.reason !== void 0 ? { reason: body.reason } : {} + }; + } + } catch (err) { + if (!detailSequencer.isCurrent(seq)) return; + detailState = { kind: "error", memberId, name, message: err instanceof Error ? err.message : String(err) }; + } + render(); + } + function closeDetail() { + detailSequencer.invalidate(); + detailState = { kind: "closed" }; + render(); + } + function bindDetail() { + detailView.querySelector("[data-detail-back]")?.addEventListener("click", closeDetail); + const reload = () => { + if (detailState.kind === "ready" || detailState.kind === "error") { + void openDetail(detailState.memberId, detailState.name); + } + }; + detailView.querySelector("[data-detail-refresh]")?.addEventListener("click", reload); + detailView.querySelector("[data-detail-retry]")?.addEventListener("click", reload); + detailView.querySelector("[data-detail-copy]")?.addEventListener("click", () => { + if (detailState.kind !== "ready") return; + void navigator.clipboard?.writeText(detailState.detail.sessionId).catch(() => void 0); + const btn = detailView.querySelector("[data-detail-copy]"); + if (btn !== null) { + btn.textContent = td(lang, "detail.copied"); + setTimeout(() => { + if (btn.isConnected) btn.textContent = td(lang, "detail.copySessionId"); + }, 1500); + } + }); + detailView.querySelector("[data-detail-earlier]")?.addEventListener("click", (ev) => { + const cursor = Number(ev.currentTarget.dataset.cursor); + if (detailState.kind === "ready" && Number.isFinite(cursor)) { + void openDetail(detailState.memberId, detailState.name, cursor); + } + }); + for (const head of detailView.querySelectorAll("button.tool-group-head")) { + head.addEventListener("click", () => { + const group = head.closest(".tool-group"); + const open2 = group?.classList.toggle("open") ?? false; + head.setAttribute("aria-expanded", open2 ? "true" : "false"); + }); + } + for (const row of detailView.querySelectorAll("button.tool-row")) { + row.addEventListener("click", () => { + const o = row.classList.toggle("open"); + row.setAttribute("aria-expanded", o ? "true" : "false"); + }); + } + } + render(); + connect(); +})(); diff --git a/external_plugins/agent-team/runtime/ui/panel.js b/external_plugins/agent-team/runtime/ui/panel.js new file mode 100644 index 00000000..b0502696 --- /dev/null +++ b/external_plugins/agent-team/runtime/ui/panel.js @@ -0,0 +1,16048 @@ +"use strict"; +(() => { + var __defProp = Object.defineProperty; + var __getOwnPropNames = Object.getOwnPropertyNames; + var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { + get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2] + }) : x)(function(x) { + if (typeof require !== "undefined") return require.apply(this, arguments); + throw Error('Dynamic require of "' + x + '" is not supported'); + }); + var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; + }; + var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); + }; + + // node_modules/zod/v4/core/core.js + // @__NO_SIDE_EFFECTS__ + function $constructor(name, initializer3, params) { + function init(inst, def) { + var _a; + Object.defineProperty(inst, "_zod", { + value: inst._zod ?? {}, + enumerable: false + }); + (_a = inst._zod).traits ?? (_a.traits = /* @__PURE__ */ new Set()); + inst._zod.traits.add(name); + initializer3(inst, def); + for (const k2 in _2.prototype) { + if (!(k2 in inst)) + Object.defineProperty(inst, k2, { value: _2.prototype[k2].bind(inst) }); + } + inst._zod.constr = _2; + inst._zod.def = def; + } + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _2(def) { + var _a; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a = inst._zod).deferred ?? (_a.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_2, "init", { value: init }); + Object.defineProperty(_2, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + } + }); + Object.defineProperty(_2, "name", { value: name }); + return _2; + } + function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; + } + var NEVER, $brand, $ZodAsyncError, globalConfig; + var init_core = __esm({ + "node_modules/zod/v4/core/core.js"() { + NEVER = Object.freeze({ + status: "aborted" + }); + $brand = Symbol("zod_brand"); + $ZodAsyncError = class extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } + }; + globalConfig = {}; + } + }); + + // node_modules/zod/v4/core/util.js + var util_exports = {}; + __export(util_exports, { + BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES, + Class: () => Class, + NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES, + aborted: () => aborted, + allowsEval: () => allowsEval, + assert: () => assert, + assertEqual: () => assertEqual, + assertIs: () => assertIs, + assertNever: () => assertNever, + assertNotEqual: () => assertNotEqual, + assignProp: () => assignProp, + cached: () => cached, + captureStackTrace: () => captureStackTrace, + cleanEnum: () => cleanEnum, + cleanRegex: () => cleanRegex, + clone: () => clone, + createTransparentProxy: () => createTransparentProxy, + defineLazy: () => defineLazy, + esc: () => esc, + escapeRegex: () => escapeRegex, + extend: () => extend, + finalizeIssue: () => finalizeIssue, + floatSafeRemainder: () => floatSafeRemainder, + getElementAtPath: () => getElementAtPath, + getEnumValues: () => getEnumValues, + getLengthableOrigin: () => getLengthableOrigin, + getParsedType: () => getParsedType, + getSizableOrigin: () => getSizableOrigin, + isObject: () => isObject, + isPlainObject: () => isPlainObject, + issue: () => issue, + joinValues: () => joinValues, + jsonStringifyReplacer: () => jsonStringifyReplacer, + merge: () => merge, + normalizeParams: () => normalizeParams, + nullish: () => nullish, + numKeys: () => numKeys, + omit: () => omit, + optionalKeys: () => optionalKeys, + partial: () => partial, + pick: () => pick, + prefixIssues: () => prefixIssues, + primitiveTypes: () => primitiveTypes, + promiseAllObject: () => promiseAllObject, + propertyKeyTypes: () => propertyKeyTypes, + randomString: () => randomString, + required: () => required, + stringifyPrimitive: () => stringifyPrimitive, + unwrapMessage: () => unwrapMessage + }); + function assertEqual(val) { + return val; + } + function assertNotEqual(val) { + return val; + } + function assertIs(_arg) { + } + function assertNever(_x) { + throw new Error(); + } + function assert(_2) { + } + function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v2) => typeof v2 === "number"); + const values = Object.entries(entries).filter(([k2, _2]) => numericValues.indexOf(+k2) === -1).map(([_2, v2]) => v2); + return values; + } + function joinValues(array2, separator = "|") { + return array2.map((val) => stringifyPrimitive(val)).join(separator); + } + function jsonStringifyReplacer(_2, value) { + if (typeof value === "bigint") + return value.toString(); + return value; + } + function cached(getter) { + const set2 = false; + return { + get value() { + if (!set2) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + } + }; + } + function nullish(input) { + return input === null || input === void 0; + } + function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); + } + function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return valInt % stepInt / 10 ** decCount; + } + function defineLazy(object3, key, getter) { + const set2 = false; + Object.defineProperty(object3, key, { + get() { + if (!set2) { + const value = getter(); + object3[key] = value; + return value; + } + throw new Error("cached value already set"); + }, + set(v2) { + Object.defineProperty(object3, key, { + value: v2 + // configurable: true, + }); + }, + configurable: true + }); + } + function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true + }); + } + function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); + } + function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i2 = 0; i2 < keys.length; i2++) { + resolvedObj[keys[i2]] = results[i2]; + } + return resolvedObj; + }); + } + function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i2 = 0; i2 < length; i2++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; + } + function esc(str) { + return JSON.stringify(str); + } + function isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); + } + function isPlainObject(o) { + if (isObject(o) === false) + return false; + const ctor = o.constructor; + if (ctor === void 0) + return true; + const prot = ctor.prototype; + if (isObject(prot) === false) + return false; + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; + } + function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; + } + function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + } + function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; + } + function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== void 0) { + if (params?.error !== void 0) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; + } + function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_2, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_2, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_2, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_2, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_2) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_2, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_2, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + } + }); + } + function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; + } + function optionalKeys(shape) { + return Object.keys(shape).filter((k2) => { + return shape[k2]._zod.optin === "optional" && shape[k2]._zod.optout === "optional"; + }); + } + function pick(schema, mask) { + const newShape = {}; + const currDef = schema._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + return clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [] + }); + } + function omit(schema, mask) { + const newShape = { ...schema._zod.def.shape }; + const currDef = schema._zod.def; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + return clone(schema, { + ...schema._zod.def, + shape: newShape, + checks: [] + }); + } + function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const def = { + ...schema._zod.def, + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + checks: [] + // delete existing checks + }; + return clone(schema, def); + } + function merge(a, b2) { + return clone(a, { + ...a._zod.def, + get shape() { + const _shape = { ...a._zod.def.shape, ...b2._zod.def.shape }; + assignProp(this, "shape", _shape); + return _shape; + }, + catchall: b2._zod.def.catchall, + checks: [] + // delete existing checks + }); + } + function partial(Class2, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } else { + for (const key in oldShape) { + shape[key] = Class2 ? new Class2({ + type: "optional", + innerType: oldShape[key] + }) : oldShape[key]; + } + } + return clone(schema, { + ...schema._zod.def, + shape, + checks: [] + }); + } + function required(Class2, schema, mask) { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } else { + for (const key in oldShape) { + shape[key] = new Class2({ + type: "nonoptional", + innerType: oldShape[key] + }); + } + } + return clone(schema, { + ...schema._zod.def, + shape, + // optional: [], + checks: [] + }); + } + function aborted(x, startIndex = 0) { + for (let i2 = startIndex; i2 < x.issues.length; i2++) { + if (x.issues[i2]?.continue !== true) + return true; + } + return false; + } + function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); + } + function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; + } + function finalizeIssue(iss, ctx, config2) { + const full = { ...iss, path: iss.path ?? [] }; + if (!iss.message) { + const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input"; + full.message = message; + } + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; + } + function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + if (input instanceof File) + return "file"; + return "unknown"; + } + function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; + } + function issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst + }; + } + return { ...iss }; + } + function cleanEnum(obj) { + return Object.entries(obj).filter(([k2, _2]) => { + return Number.isNaN(Number.parseInt(k2, 10)); + }).map((el) => el[1]); + } + var captureStackTrace, allowsEval, getParsedType, propertyKeyTypes, primitiveTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, Class; + var init_util = __esm({ + "node_modules/zod/v4/core/util.js"() { + captureStackTrace = Error.captureStackTrace ? Error.captureStackTrace : (..._args) => { + }; + allowsEval = cached(() => { + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F2 = Function; + new F2(""); + return true; + } catch (_2) { + return false; + } + }); + getParsedType = (data) => { + const t2 = typeof data; + switch (t2) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t2}`); + } + }; + propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]); + primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); + NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-34028234663852886e22, 34028234663852886e22], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE] + }; + BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")], + uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")] + }; + Class = class { + constructor(..._args) { + } + }; + } + }); + + // node_modules/zod/v4/core/errors.js + function flattenError(error40, mapper = (issue2) => issue2.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error40.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + function formatError(error40, _mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error41) => { + for (const issue2 of error41.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues })); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }); + } else if (issue2.path.length === 0) { + fieldErrors._errors.push(mapper(issue2)); + } else { + let curr = fieldErrors; + let i2 = 0; + while (i2 < issue2.path.length) { + const el = issue2.path[i2]; + const terminal = i2 === issue2.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue2)); + } + curr = curr[el]; + i2++; + } + } + } + }; + processError(error40); + return fieldErrors; + } + function treeifyError(error40, _mapper) { + const mapper = _mapper || function(issue2) { + return issue2.message; + }; + const result = { errors: [] }; + const processError = (error41, path = []) => { + var _a, _b; + for (const issue2 of error41.issues) { + if (issue2.code === "invalid_union" && issue2.errors.length) { + issue2.errors.map((issues) => processError({ issues }, issue2.path)); + } else if (issue2.code === "invalid_key") { + processError({ issues: issue2.issues }, issue2.path); + } else if (issue2.code === "invalid_element") { + processError({ issues: issue2.issues }, issue2.path); + } else { + const fullpath = [...path, ...issue2.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue2)); + continue; + } + let curr = result; + let i2 = 0; + while (i2 < fullpath.length) { + const el = fullpath[i2]; + const terminal = i2 === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); + curr = curr.properties[el]; + } else { + curr.items ?? (curr.items = []); + (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue2)); + } + i2++; + } + } + } + }; + processError(error40); + return result; + } + function toDotPath(path) { + const segs = []; + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); + } + function prettifyError(error40) { + const lines = []; + const issues = [...error40.issues].sort((a, b2) => a.path.length - b2.path.length); + for (const issue2 of issues) { + lines.push(`\u2716 ${issue2.message}`); + if (issue2.path?.length) + lines.push(` \u2192 at ${toDotPath(issue2.path)}`); + } + return lines.join("\n"); + } + var initializer, $ZodError, $ZodRealError; + var init_errors = __esm({ + "node_modules/zod/v4/core/errors.js"() { + init_core(); + init_util(); + initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false + }); + Object.defineProperty(inst, "message", { + get() { + return JSON.stringify(def, jsonStringifyReplacer, 2); + }, + enumerable: true + // configurable: false, + }); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false + }); + }; + $ZodError = $constructor("$ZodError", initializer); + $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); + } + }); + + // node_modules/zod/v4/core/parse.js + var _parse, parse, _parseAsync, parseAsync, _safeParse, safeParse, _safeParseAsync, safeParseAsync; + var init_parse = __esm({ + "node_modules/zod/v4/core/parse.js"() { + init_core(); + init_errors(); + init_util(); + _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; + }; + parse = /* @__PURE__ */ _parse($ZodRealError); + _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; + }; + parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError); + _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; + }; + safeParse = /* @__PURE__ */ _safeParse($ZodRealError); + _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + } : { success: true, data: result.value }; + }; + safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError); + } + }); + + // node_modules/zod/v4/core/regexes.js + var regexes_exports = {}; + __export(regexes_exports, { + _emoji: () => _emoji, + base64: () => base64, + base64url: () => base64url, + bigint: () => bigint, + boolean: () => boolean, + browserEmail: () => browserEmail, + cidrv4: () => cidrv4, + cidrv6: () => cidrv6, + cuid: () => cuid, + cuid2: () => cuid2, + date: () => date, + datetime: () => datetime, + domain: () => domain, + duration: () => duration, + e164: () => e164, + email: () => email, + emoji: () => emoji, + extendedDuration: () => extendedDuration, + guid: () => guid, + hostname: () => hostname, + html5Email: () => html5Email, + integer: () => integer, + ipv4: () => ipv4, + ipv6: () => ipv6, + ksuid: () => ksuid, + lowercase: () => lowercase, + nanoid: () => nanoid, + null: () => _null, + number: () => number, + rfc5322Email: () => rfc5322Email, + string: () => string, + time: () => time, + ulid: () => ulid, + undefined: () => _undefined, + unicodeEmail: () => unicodeEmail, + uppercase: () => uppercase, + uuid: () => uuid, + uuid4: () => uuid4, + uuid6: () => uuid6, + uuid7: () => uuid7, + xid: () => xid + }); + function emoji() { + return new RegExp(_emoji, "u"); + } + function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; + } + function time(args) { + return new RegExp(`^${timeSource(args)}$`); + } + function datetime(args) { + const time3 = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + if (args.offset) + opts.push(`([+-]\\d{2}:\\d{2})`); + const timeRegex = `${time3}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); + } + var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, extendedDuration, guid, uuid, uuid4, uuid6, uuid7, email, html5Email, rfc5322Email, unicodeEmail, browserEmail, _emoji, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, hostname, domain, e164, dateSource, date, string, bigint, integer, number, boolean, _null, _undefined, lowercase, uppercase; + var init_regexes = __esm({ + "node_modules/zod/v4/core/regexes.js"() { + cuid = /^[cC][^\s-]{8,}$/; + cuid2 = /^[0-9a-z]+$/; + ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; + xid = /^[0-9a-vA-V]{20}$/; + ksuid = /^[A-Za-z0-9]{27}$/; + nanoid = /^[a-zA-Z0-9_-]{21}$/; + duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; + extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; + guid = /^([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})$/; + uuid = (version2) => { + if (!version2) + return /^([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)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); + }; + uuid4 = /* @__PURE__ */ uuid(4); + uuid6 = /* @__PURE__ */ uuid(6); + uuid7 = /* @__PURE__ */ uuid(7); + email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; + html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; + browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; + _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; + ipv4 = /^(?:(?: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])$/; + ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/; + cidrv4 = /^((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])$/; + cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; + base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; + base64url = /^[A-Za-z0-9_-]*$/; + hostname = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; + domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; + e164 = /^\+(?:[0-9]){6,14}[0-9]$/; + dateSource = `(?:(?:\\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])))`; + date = /* @__PURE__ */ new RegExp(`^${dateSource}$`); + string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); + }; + bigint = /^\d+n?$/; + integer = /^\d+$/; + number = /^-?\d+(?:\.\d+)?/i; + boolean = /true|false/i; + _null = /null/i; + _undefined = /undefined/i; + lowercase = /^[^A-Z]*$/; + uppercase = /^[^a-z]*$/; + } + }); + + // node_modules/zod/v4/core/checks.js + function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...prefixIssues(property, result.issues)); + } + } + var $ZodCheck, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckBigIntFormat, $ZodCheckMaxSize, $ZodCheckMinSize, $ZodCheckSizeEquals, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckProperty, $ZodCheckMimeType, $ZodCheckOverwrite; + var init_checks = __esm({ + "node_modules/zod/v4/core/checks.js"() { + init_core(); + init_regexes(); + init_util(); + $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); + }); + numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date" + }; + $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_big", + maximum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_small", + minimum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + var _a; + (_a = inst2._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + input, + inst + }); + return; + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort + }); + } else { + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inst + }); + } + }; + }); + $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inst + }); + } + }; + }); + $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: getSizableOrigin(input), + ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.maximum ?? Number.POSITIVE_INFINITY; + if (def.maximum < curr) + inst2._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const curr = inst2._zod.bag.minimum ?? Number.NEGATIVE_INFINITY; + if (def.minimum > curr) + inst2._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== void 0; + }); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }, + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...def.pattern ? { pattern: def.pattern.toString() } : {}, + inst, + continue: !def.abort + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { + }); + }); + $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); + }); + $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); + }); + $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [] + }, {}); + if (result instanceof Promise) { + return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; + }); + $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst + }); + }; + }); + $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; + }); + } + }); + + // node_modules/zod/v4/core/doc.js + var Doc; + var init_doc = __esm({ + "node_modules/zod/v4/core/doc.js"() { + Doc = class { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F2 = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + return new F2(...args, lines.join("\n")); + } + }; + } + }); + + // node_modules/zod/v4/core/versions.js + var version; + var init_versions = __esm({ + "node_modules/zod/v4/core/versions.js"() { + version = { + major: 4, + minor: 0, + patch: 0 + }; + } + }); + + // node_modules/zod/v4/core/schemas.js + function isValidBase64(data) { + if (data === "") + return true; + if (data.length % 4 !== 0) + return false; + try { + atob(data); + return true; + } catch { + return false; + } + } + function isValidBase64URL(data) { + if (!base64url.test(data)) + return false; + const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/"); + const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "="); + return isValidBase64(padded); + } + function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } catch { + return false; + } + } + function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; + } + function handleObjectResult(result, final, key) { + if (result.issues.length) { + final.issues.push(...prefixIssues(key, result.issues)); + } + final.value[key] = result.value; + } + function handleOptionalObjectResult(result, final, key, input) { + if (result.issues.length) { + if (input[key] === void 0) { + if (key in input) { + final.value[key] = void 0; + } else { + final.value[key] = result.value; + } + } else { + final.issues.push(...prefixIssues(key, result.issues)); + } + } else if (result.value === void 0) { + if (key in input) + final.value[key] = void 0; + } else { + final.value[key] = result.value; + } + } + function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))) + }); + return final; + } + function mergeValues(a, b2) { + if (a === b2) { + return { valid: true, data: a }; + } + if (a instanceof Date && b2 instanceof Date && +a === +b2) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b2)) { + const bKeys = Object.keys(b2); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b2 }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b2[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath] + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b2)) { + if (a.length !== b2.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b2[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath] + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; + } + function handleIntersectionResults(result, left, right) { + if (left.issues.length) { + result.issues.push(...left.issues); + } + if (right.issues.length) { + result.issues.push(...right.issues); + } + if (aborted(result)) + return result; + const merged = mergeValues(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; + } + function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; + } + function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, keyResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_key", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, valueResult.issues)); + } else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key, + issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }); + } + } + final.value.set(keyResult.value, valueResult.value); + } + function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); + } + function handleDefaultResult(payload, def) { + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return payload; + } + function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === void 0) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst + }); + } + return payload; + } + function handlePipeResult(left, def, ctx) { + if (aborted(left)) { + return left; + } + return def.out._zod.run({ value: left.value, issues: left.issues }, ctx); + } + function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; + } + function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, + // incorporates params.error into issue reporting + path: [...inst._zod.def.path ?? []], + // incorporates params.error into issue reporting + continue: !inst._zod.def.abort + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(issue(_iss)); + } + } + var $ZodType, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, $ZodBase64, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodCustomStringFormat, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodBigInt, $ZodBigIntFormat, $ZodSymbol, $ZodUndefined, $ZodNull, $ZodAny, $ZodUnknown, $ZodNever, $ZodVoid, $ZodDate, $ZodArray, $ZodObject, $ZodUnion, $ZodDiscriminatedUnion, $ZodIntersection, $ZodTuple, $ZodRecord, $ZodMap, $ZodSet, $ZodEnum, $ZodLiteral, $ZodFile, $ZodTransform, $ZodOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodSuccess, $ZodCatch, $ZodNaN, $ZodPipe, $ZodReadonly, $ZodTemplateLiteral, $ZodPromise, $ZodLazy, $ZodCustom; + var init_schemas = __esm({ + "node_modules/zod/v4/core/schemas.js"() { + init_checks(); + init_core(); + init_doc(); + init_parse(); + init_regexes(); + init_util(); + init_versions(); + init_util(); + $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; + inst._zod.bag = inst._zod.bag || {}; + inst._zod.version = version; + const checks = [...inst._zod.def.checks ?? []]; + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } else { + const runChecks = (payload, checks2, ctx) => { + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks2) { + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _2 = ch._zod.check(payload); + if (_2 instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _2 instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _2; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + inst._zod.run = (payload, ctx) => { + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result2) => runChecks(result2, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + inst["~standard"] = { + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } catch (_2) { + return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues }); + } + }, + vendor: "zod", + version: 1 + }; + }); + $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _2) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } catch (_3) { + } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); + }); + $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); + }); + $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8 + }; + const v2 = versionMap[def.version]; + if (v2 === void 0) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v2)); + } else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); + }); + $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); + }); + $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + const orig = payload.value; + const url2 = new URL(orig); + const href = url2.href; + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url2.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: hostname.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort + }); + } + } + if (!orig.endsWith("/") && href.endsWith("/")) { + payload.value = href.slice(0, -1); + } else { + payload.value = href; + } + return; + } catch (_2) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); + }); + $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); + }); + $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); + }); + $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); + }); + $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); + }); + $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); + }); + $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); + }); + $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + }); + $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); + }); + $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time(def)); + $ZodStringFormat.init(inst, def); + }); + $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); + }); + $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = `ipv4`; + }); + }); + $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + const bag = inst2._zod.bag; + bag.format = `ipv6`; + }); + inst._zod.check = (payload) => { + try { + new URL(`http://[${payload.value}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); + }); + $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const [address, prefix] = payload.value.split("/"); + try { + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + new URL(`http://[${address}]`); + } catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort + }); + } + }; + }); + $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.contentEncoding = "base64"; + }); + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url); + $ZodStringFormat.init(inst, def); + inst._zod.onattach.push((inst2) => { + inst2._zod.bag.contentEncoding = "base64url"; + }); + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); + }); + $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort + }); + }; + }); + $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } catch (_2) { + } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...received ? { received } : {} + }); + return payload; + }; + }); + $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); + }); + $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } catch (_2) { + } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } catch (_2) { + } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => { + $ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); + }); + $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _undefined; + inst._zod.values = /* @__PURE__ */ new Set([void 0]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = /* @__PURE__ */ new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; + }); + $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst + }); + return payload; + }; + }); + $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } catch (_err) { + } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...isDate ? { received: "Invalid Date" } : {}, + inst + }); + return payload; + }; + }); + $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i2 = 0; i2 < input.length; i2++) { + const item = input[i2]; + const result = def.element._zod.run({ + value: item, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleArrayResult(result2, payload, i2))); + } else { + handleArrayResult(result, payload, i2); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; + }); + $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => { + $ZodType.init(inst, def); + const _normalized = cached(() => { + const keys = Object.keys(def.shape); + for (const k2 of keys) { + if (!(def.shape[k2] instanceof $ZodType)) { + throw new Error(`Invalid element at key "${k2}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + shape: def.shape, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys) + }; + }); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set()); + for (const v2 of field.values) + propValues[key].add(v2); + } + } + return propValues; + }); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k2 = esc(key); + return `shape[${k2}]._zod.run({ value: input[${k2}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = /* @__PURE__ */ Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + doc.write(`const newResult = {}`); + for (const key of normalized.keys) { + if (normalized.optionalKeys.has(key)) { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + const k2 = esc(key); + doc.write(` + if (${id}.issues.length) { + if (input[${k2}] === undefined) { + if (${k2} in input) { + newResult[${k2}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${id}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${k2}, ...iss.path] : [${k2}], + })) + ); + } + } else if (${id}.value === undefined) { + if (${k2} in input) newResult[${k2}] = undefined; + } else { + newResult[${k2}] = ${id}.value; + } + `); + } else { + const id = ids[key]; + doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(` + if (${id}.issues.length) payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${esc(key)}, ...iss.path] : [${esc(key)}] + })));`); + doc.write(`newResult[${esc(key)}] = ${id}.value`); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject2 = isObject; + const jit = !globalConfig.jitless; + const allowsEval2 = allowsEval; + const fastEnabled = jit && allowsEval2.value; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject2(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + } else { + payload.value = {}; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + const isOptional = el._zod.optin === "optional" && el._zod.optout === "optional"; + if (r instanceof Promise) { + proms.push(r.then((r2) => isOptional ? handleOptionalObjectResult(r2, payload, key, input) : handleObjectResult(r2, payload, key))); + } else if (isOptional) { + handleOptionalObjectResult(r, payload, key, input); + } else { + handleObjectResult(r, payload, key); + } + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + const unrecognized = []; + const keySet = value.keySet; + const _catchall = catchall._zod; + const t2 = _catchall.def.type; + for (const key of Object.keys(input)) { + if (keySet.has(key)) + continue; + if (t2 === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r2) => handleObjectResult(r2, payload, key))); + } else { + handleObjectResult(r, payload, key); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); + }; + }); + $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return void 0; + }); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p2) => cleanRegex(p2.source)).join("|")})$`); + } + return void 0; + }); + inst._zod.parse = (payload, ctx) => { + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [] + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results2) => { + return handleUnionResults(results2, payload, inst, ctx); + }); + }; + }); + $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => { + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k2, v2] of Object.entries(pv)) { + if (!propValues[k2]) + propValues[k2] = /* @__PURE__ */ new Set(); + for (const val of v2) { + propValues[k2].add(val); + } + } + } + return propValues; + }); + const disc = cached(() => { + const opts = def.options; + const map2 = /* @__PURE__ */ new Map(); + for (const o of opts) { + const values = o._zod.propValues[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v2 of values) { + if (map2.has(v2)) { + throw new Error(`Duplicate discriminator value "${String(v2)}"`); + } + map2.set(v2, o); + } + } + return map2; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + if (def.unionFallback) { + return _super(payload, ctx); + } + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + input, + path: [def.discriminator], + inst + }); + return payload; + }; + }); + $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left2, right2]) => { + return handleIntersectionResults(payload, left2, right2); + }); + } + return handleIntersectionResults(payload, left, right); + }; + }); + $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const optStart = items.length - [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type" + }); + return payload; + } + payload.value = []; + const proms = []; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + input, + inst, + origin: "array", + ...tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length } + }); + return payload; + } + } + let i2 = -1; + for (const item of items) { + i2++; + if (i2 >= input.length) { + if (i2 >= optStart) + continue; + } + const result = item._zod.run({ + value: input[i2], + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload, i2))); + } else { + handleTupleResult(result, payload, i2); + } + } + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i2++; + const result = def.rest._zod.run({ + value: el, + issues: [] + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleTupleResult(result2, payload, i2))); + } else { + handleTupleResult(result, payload, i2); + } + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + if (def.keyType._zod.values) { + const values = def.keyType._zod.values; + payload.value = {}; + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[key] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!values.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized + }); + } + } else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + origin: "record", + code: "invalid_key", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst + }); + payload.value[keyResult.value] = keyResult.value; + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => { + if (result2.issues.length) { + payload.issues.push(...prefixIssues(key, result2.issues)); + } + payload.value[keyResult.value] = result2.value; + })); + } else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; + }); + $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => { + handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx); + })); + } else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type" + }); + return payload; + } + const proms = []; + payload.value = /* @__PURE__ */ new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result2) => handleSetResult(result2, payload))); + } else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; + }); + $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + inst._zod.values = new Set(values); + inst._zod.pattern = new RegExp(`^(${values.filter((k2) => propertyKeyTypes.has(typeof k2)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst + }); + return payload; + }; + }); + $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.values = new Set(def.values); + inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? o.toString() : String(o)).join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (inst._zod.values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst + }); + return payload; + }; + }); + $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst + }); + return payload; + }; + }); + $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const _out = def.transform(payload.value, payload); + if (_ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output2) => { + payload.value = output2; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; + }); + $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + return def.innerType._zod.run(payload, ctx); + } + if (payload.value === void 0) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === void 0) { + payload.value = def.defaultValue; + return payload; + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleDefaultResult(result2, def)); + } + return handleDefaultResult(result, def); + }; + }); + $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (payload.value === void 0) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; + }); + $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v2 = def.innerType._zod.values; + return v2 ? new Set([...v2].filter((x) => x !== void 0)) : void 0; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => handleNonOptionalResult(result2, inst)); + } + return handleNonOptionalResult(result, inst); + }; + }); + $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; + }); + $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result2) => { + payload.value = result2.value; + if (result2.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }); + } + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) + }, + input: payload.value + }); + payload.issues = []; + } + return payload; + }; + }); + $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type" + }); + return payload; + } + return payload; + }; + }); + $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + inst._zod.parse = (payload, ctx) => { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left2) => handlePipeResult(left2, def, ctx)); + } + return handlePipeResult(left, def, ctx); + }; + }); + $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; + }); + $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (part instanceof $ZodType) { + if (!part._zod.pattern) { + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } else if (part === null || primitiveTypes.has(typeof part)) { + regexParts.push(escapeRegex(`${part}`)); + } else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "template_literal", + code: "invalid_type" + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: "template_literal", + pattern: inst._zod.pattern.source + }); + return payload; + } + return payload; + }; + }); + $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; + }); + $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "innerType", () => def.getter()); + defineLazy(inst._zod, "pattern", () => inst._zod.innerType._zod.pattern); + defineLazy(inst._zod, "propValues", () => inst._zod.innerType._zod.propValues); + defineLazy(inst._zod, "optin", () => inst._zod.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => inst._zod.innerType._zod.optout); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; + }); + $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _2) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r2) => handleRefineResult(r2, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; + }); + } + }); + + // node_modules/zod/v4/locales/ar.js + function ar_default() { + return { + localeError: error() + }; + } + var error; + var init_ar = __esm({ + "node_modules/zod/v4/locales/ar.js"() { + init_util(); + error = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, + set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0645\u062F\u062E\u0644", + email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", + url: "\u0631\u0627\u0628\u0637", + emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", + ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", + ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", + cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", + cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", + base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", + base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", + json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", + e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", + jwt: "JWT", + template_literal: "\u0645\u062F\u062E\u0644" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"}`; + return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${issue2.origin ?? "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`; + if (_issue.format === "ends_with") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`; + } + case "not_multiple_of": + return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`; + case "unrecognized_keys": + return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + case "invalid_union": + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + case "invalid_element": + return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`; + default: + return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/az.js + function az_default() { + return { + localeError: error2() + }; + } + var error2; + var init_az = __esm({ + "node_modules/zod/v4/locales/az.js"() { + init_util(); + error2 = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "element", verb: "olmal\u0131d\u0131r" }, + set: { unit: "element", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + 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", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${issue2.expected}, daxil olan ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`; + return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${issue2.origin ?? "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`; + if (_issue.format === "ends_with") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`; + if (_issue.format === "includes") + return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`; + if (_issue.format === "regex") + return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`; + return `Yanl\u0131\u015F ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`; + case "unrecognized_keys": + return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`; + case "invalid_union": + return "Yanl\u0131\u015F d\u0259y\u0259r"; + case "invalid_element": + return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`; + default: + return `Yanl\u0131\u015F d\u0259y\u0259r`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/be.js + function getBelarusianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; + } + function be_default() { + return { + localeError: error3() + }; + } + var error3; + var init_be = __esm({ + "node_modules/zod/v4/locales/be.js"() { + init_util(); + error3 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0456\u043C\u0432\u0430\u043B", + few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", + many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u044B", + many: "\u0431\u0430\u0439\u0442\u0430\u045E" + }, + verb: "\u043C\u0435\u0446\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u043B\u0456\u043A"; + } + case "object": { + if (Array.isArray(data)) { + return "\u043C\u0430\u0441\u0456\u045E"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0443\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0430\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0447\u0430\u0441", + duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", + cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", + base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", + base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", + json_string: "JSON \u0440\u0430\u0434\u043E\u043A", + e164: "\u043D\u0443\u043C\u0430\u0440 E.164", + jwt: "JWT", + template_literal: "\u0443\u0432\u043E\u0434" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"; + case "invalid_element": + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`; + default: + return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ca.js + function ca_default() { + return { + localeError: error4() + }; + } + var error4; + var init_ca = __esm({ + "node_modules/zod/v4/locales/ca.js"() { + init_util(); + error4 = () => { + const Sizable = { + string: { unit: "car\xE0cters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "entrada", + email: "adre\xE7a electr\xF2nica", + 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: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adre\xE7a IPv4", + ipv6: "adre\xE7a IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Tipus inv\xE0lid: s'esperava ${issue2.expected}, s'ha rebut ${parsedType4(issue2.input)}`; + // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`; + case "too_big": { + const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue2.origin ?? "el valor"} fos ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`; + return `Format inv\xE0lid per a ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Clau inv\xE0lida a ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE0lida"; + // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element inv\xE0lid a ${issue2.origin}`; + default: + return `Entrada inv\xE0lida`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/cs.js + function cs_default() { + return { + localeError: error5() + }; + } + var error5; + var init_cs = __esm({ + "node_modules/zod/v4/locales/cs.js"() { + init_util(); + error5 = () => { + const Sizable = { + string: { unit: "znak\u016F", verb: "m\xEDt" }, + file: { unit: "bajt\u016F", verb: "m\xEDt" }, + array: { unit: "prvk\u016F", verb: "m\xEDt" }, + set: { unit: "prvk\u016F", verb: "m\xEDt" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u010D\xEDslo"; + } + case "string": { + return "\u0159et\u011Bzec"; + } + case "boolean": { + return "boolean"; + } + case "bigint": { + return "bigint"; + } + case "function": { + return "funkce"; + } + case "symbol": { + return "symbol"; + } + case "undefined": { + return "undefined"; + } + case "object": { + if (Array.isArray(data)) { + return "pole"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "regul\xE1rn\xED v\xFDraz", + email: "e-mailov\xE1 adresa", + 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: "datum a \u010Das ve form\xE1tu ISO", + date: "datum ve form\xE1tu ISO", + time: "\u010Das ve form\xE1tu ISO", + duration: "doba trv\xE1n\xED ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", + base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", + json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", + e164: "\u010D\xEDslo E.164", + jwt: "JWT", + template_literal: "vstup" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${issue2.expected}, obdr\u017Eeno ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`; + return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "prvk\u016F"}`; + } + return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${issue2.origin ?? "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`; + return `Neplatn\xFD form\xE1t ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`; + case "unrecognized_keys": + return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neplatn\xFD vstup"; + case "invalid_element": + return `Neplatn\xE1 hodnota v ${issue2.origin}`; + default: + return `Neplatn\xFD vstup`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/de.js + function de_default() { + return { + localeError: error6() + }; + } + var error6; + var init_de = __esm({ + "node_modules/zod/v4/locales/de.js"() { + init_util(); + error6 = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "Zahl"; + } + case "object": { + if (Array.isArray(data)) { + return "Array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "Eingabe", + email: "E-Mail-Adresse", + 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-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Ung\xFCltige Eingabe: erwartet ${issue2.expected}, erhalten ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`; + return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu gro\xDF: erwartet, dass ${issue2.origin ?? "Wert"} ${adj}${issue2.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ung\xFCltig: ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`; + case "invalid_union": + return "Ung\xFCltige Eingabe"; + case "invalid_element": + return `Ung\xFCltiger Wert in ${issue2.origin}`; + default: + return `Ung\xFCltige Eingabe`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/en.js + function en_default() { + return { + localeError: error7() + }; + } + var parsedType, error7; + var init_en = __esm({ + "node_modules/zod/v4/locales/en.js"() { + init_util(); + parsedType = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + error7 = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + 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", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Invalid input: expected ${issue2.expected}, received ${parsedType(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Too big: expected ${issue2.origin ?? "value"} to have ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue2.origin ?? "value"} to be ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue2.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue2.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue2.origin}`; + default: + return `Invalid input`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/eo.js + function eo_default() { + return { + localeError: error8() + }; + } + var parsedType2, error8; + var init_eo = __esm({ + "node_modules/zod/v4/locales/eo.js"() { + init_util(); + parsedType2 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombro"; + } + case "object": { + if (Array.isArray(data)) { + return "tabelo"; + } + if (data === null) { + return "senvalora"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + error8 = () => { + const Sizable = { + string: { unit: "karaktrojn", verb: "havi" }, + file: { unit: "bajtojn", verb: "havi" }, + array: { unit: "elementojn", verb: "havi" }, + set: { unit: "elementojn", verb: "havi" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "enigo", + email: "retadreso", + url: "URL", + emoji: "emo\u011Dio", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datotempo", + date: "ISO-dato", + time: "ISO-tempo", + duration: "ISO-da\u016Dro", + ipv4: "IPv4-adreso", + ipv6: "IPv6-adreso", + cidrv4: "IPv4-rango", + cidrv6: "IPv6-rango", + base64: "64-ume kodita karaktraro", + base64url: "URL-64-ume kodita karaktraro", + json_string: "JSON-karaktraro", + e164: "E.164-nombro", + jwt: "JWT", + template_literal: "enigo" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Nevalida enigo: atendi\u011Dis ${issue2.expected}, ricevi\u011Dis ${parsedType2(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`; + return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementojn"}`; + return `Tro granda: atendi\u011Dis ke ${issue2.origin ?? "valoro"} havu ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; + return `Nevalida ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nevalida \u015Dlosilo en ${issue2.origin}`; + case "invalid_union": + return "Nevalida enigo"; + case "invalid_element": + return `Nevalida valoro en ${issue2.origin}`; + default: + return `Nevalida enigo`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/es.js + function es_default() { + return { + localeError: error9() + }; + } + var error9; + var init_es = __esm({ + "node_modules/zod/v4/locales/es.js"() { + init_util(); + error9 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "n\xFAmero"; + } + case "object": { + if (Array.isArray(data)) { + return "arreglo"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "entrada", + email: "direcci\xF3n de correo electr\xF3nico", + 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: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duraci\xF3n ISO", + ipv4: "direcci\xF3n IPv4", + ipv6: "direcci\xF3n IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Entrada inv\xE1lida: se esperaba ${issue2.expected}, recibido ${parsedType4(issue2.input)}`; + // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`; + return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} tuviera ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${issue2.origin ?? "valor"} fuera ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado peque\xF1o: se esperaba que ${issue2.origin} fuera ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`; + return `Inv\xE1lido ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Llave inv\xE1lida en ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido en ${issue2.origin}`; + default: + return `Entrada inv\xE1lida`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/fa.js + function fa_default() { + return { + localeError: error10() + }; + } + var error10; + var init_fa = __esm({ + "node_modules/zod/v4/locales/fa.js"() { + init_util(); + error10 = () => { + const Sizable = { + string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, + set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F"; + } + case "object": { + if (Array.isArray(data)) { + return "\u0622\u0631\u0627\u06CC\u0647"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0648\u0631\u0648\u062F\u06CC", + email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", + url: "URL", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", + time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", + ipv4: "IPv4 \u0622\u062F\u0631\u0633", + ipv6: "IPv6 \u0622\u062F\u0631\u0633", + cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", + cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", + base64: "base64-encoded \u0631\u0634\u062A\u0647", + base64url: "base64url-encoded \u0631\u0634\u062A\u0647", + json_string: "JSON \u0631\u0634\u062A\u0647", + e164: "E.164 \u0639\u062F\u062F", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u06CC" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${parsedType4(issue2.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`; + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`; + } + return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${issue2.origin ?? "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`; + } + return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`; + } + if (_issue.format === "ends_with") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`; + } + if (_issue.format === "includes") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`; + } + if (_issue.format === "regex") { + return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`; + } + return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + case "not_multiple_of": + return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`; + case "unrecognized_keys": + return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`; + case "invalid_union": + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + case "invalid_element": + return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`; + default: + return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/fi.js + function fi_default() { + return { + localeError: error11() + }; + } + var error11; + var init_fi = __esm({ + "node_modules/zod/v4/locales/fi.js"() { + init_util(); + error11 = () => { + const Sizable = { + string: { unit: "merkki\xE4", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "s\xE4\xE4nn\xF6llinen lauseke", + email: "s\xE4hk\xF6postiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Virheellinen tyyppi: odotettiin ${issue2.expected}, oli ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`; + return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen sy\xF6te`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/fr.js + function fr_default() { + return { + localeError: error12() + }; + } + var error12; + var init_fr = __esm({ + "node_modules/zod/v4/locales/fr.js"() { + init_util(); + error12 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombre"; + } + case "object": { + if (Array.isArray(data)) { + return "tableau"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "entr\xE9e", + email: "adresse e-mail", + 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: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Entr\xE9e invalide : ${issue2.expected} attendu, ${parsedType4(issue2.input)} re\xE7u`; + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`; + return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : ${issue2.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xE9l\xE9ment(s)"}`; + return `Trop grand : ${issue2.origin ?? "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/fr-CA.js + function fr_CA_default() { + return { + localeError: error13() + }; + } + var error13; + var init_fr_CA = __esm({ + "node_modules/zod/v4/locales/fr-CA.js"() { + init_util(); + error13 = () => { + const Sizable = { + string: { unit: "caract\xE8res", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "\xE9l\xE9ments", verb: "avoir" }, + set: { unit: "\xE9l\xE9ments", verb: "avoir" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "entr\xE9e", + email: "adresse courriel", + 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: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "dur\xE9e ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "cha\xEEne encod\xE9e en base64", + base64url: "cha\xEEne encod\xE9e en base64url", + json_string: "cha\xEEne JSON", + e164: "num\xE9ro E.164", + jwt: "JWT", + template_literal: "entr\xE9e" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Entr\xE9e invalide : attendu ${issue2.expected}, re\xE7u ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u2264" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue2.origin ?? "la valeur"} soit ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u2265" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue2.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`; + case "unrecognized_keys": + return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Cl\xE9 invalide dans ${issue2.origin}`; + case "invalid_union": + return "Entr\xE9e invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue2.origin}`; + default: + return `Entr\xE9e invalide`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/he.js + function he_default() { + return { + localeError: error14() + }; + } + var error14; + var init_he = __esm({ + "node_modules/zod/v4/locales/he.js"() { + init_util(); + error14 = () => { + const Sizable = { + string: { unit: "\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, + file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, + array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, + set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u05E7\u05DC\u05D8", + email: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", + url: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", + emoji: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", + date: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", + time: "\u05D6\u05DE\u05DF ISO", + duration: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", + ipv4: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", + ipv6: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", + cidrv4: "\u05D8\u05D5\u05D5\u05D7 IPv4", + cidrv6: "\u05D8\u05D5\u05D5\u05D7 IPv6", + base64: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", + base64url: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", + json_string: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", + e164: "\u05DE\u05E1\u05E4\u05E8 E.164", + jwt: "JWT", + template_literal: "\u05E7\u05DC\u05D8" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${parsedType4(issue2.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${stringifyPrimitive(issue2.values[0])}`; + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${issue2.origin ?? "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${issue2.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue2.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; + } + case "not_multiple_of": + return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`; + case "unrecognized_keys": + return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`; + case "invalid_union": + return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"; + case "invalid_element": + return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${issue2.origin}`; + default: + return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/hu.js + function hu_default() { + return { + localeError: error15() + }; + } + var error15; + var init_hu = __esm({ + "node_modules/zod/v4/locales/hu.js"() { + init_util(); + error15 = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "sz\xE1m"; + } + case "object": { + if (Array.isArray(data)) { + return "t\xF6mb"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "bemenet", + email: "email c\xEDm", + 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 id\u0151b\xE9lyeg", + date: "ISO d\xE1tum", + time: "ISO id\u0151", + duration: "ISO id\u0151intervallum", + ipv4: "IPv4 c\xEDm", + ipv6: "IPv6 c\xEDm", + cidrv4: "IPv4 tartom\xE1ny", + cidrv6: "IPv6 tartom\xE1ny", + base64: "base64-k\xF3dolt string", + base64url: "base64url-k\xF3dolt string", + json_string: "JSON string", + e164: "E.164 sz\xE1m", + jwt: "JWT", + template_literal: "bemenet" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${issue2.expected}, a kapott \xE9rt\xE9k ${parsedType4(issue2.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`; + return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `T\xFAl nagy: ${issue2.origin ?? "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${issue2.origin ?? "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`; + if (_issue.format === "ends_with") + return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`; + if (_issue.format === "includes") + return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`; + if (_issue.format === "regex") + return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`; + return `\xC9rv\xE9nytelen ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`; + case "invalid_union": + return "\xC9rv\xE9nytelen bemenet"; + case "invalid_element": + return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`; + default: + return `\xC9rv\xE9nytelen bemenet`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/id.js + function id_default() { + return { + localeError: error16() + }; + } + var error16; + var init_id = __esm({ + "node_modules/zod/v4/locales/id.js"() { + init_util(); + error16 = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "input", + email: "alamat email", + 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: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Input tidak valid: diharapkan ${issue2.expected}, diterima ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} memiliki ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue2.origin ?? "value"} menjadi ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue2.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue2.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue2.origin}`; + default: + return `Input tidak valid`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/it.js + function it_default() { + return { + localeError: error17() + }; + } + var error17; + var init_it = __esm({ + "node_modules/zod/v4/locales/it.js"() { + init_util(); + error17 = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numero"; + } + case "object": { + if (Array.isArray(data)) { + return "vettore"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "input", + email: "indirizzo email", + 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: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Input non valido: atteso ${issue2.expected}, ricevuto ${parsedType4(issue2.input)}`; + // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`; + return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Troppo grande: ${issue2.origin ?? "valore"} deve avere ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue2.origin ?? "valore"} deve essere ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`; + case "unrecognized_keys": + return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue2.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue2.origin}`; + default: + return `Input non valido`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ja.js + function ja_default() { + return { + localeError: error18() + }; + } + var error18; + var init_ja = __esm({ + "node_modules/zod/v4/locales/ja.js"() { + init_util(); + error18 = () => { + const Sizable = { + string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, + file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, + array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, + set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u6570\u5024"; + } + case "object": { + if (Array.isArray(data)) { + return "\u914D\u5217"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u5165\u529B\u5024", + email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", + url: "URL", + emoji: "\u7D75\u6587\u5B57", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u6642", + date: "ISO\u65E5\u4ED8", + time: "ISO\u6642\u523B", + duration: "ISO\u671F\u9593", + ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", + ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", + cidrv4: "IPv4\u7BC4\u56F2", + cidrv6: "IPv6\u7BC4\u56F2", + base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", + json_string: "JSON\u6587\u5B57\u5217", + e164: "E.164\u756A\u53F7", + jwt: "JWT", + template_literal: "\u5165\u529B\u5024" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u7121\u52B9\u306A\u5165\u529B: ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${parsedType4(issue2.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`; + return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "too_big": { + const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${sizing.unit ?? "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5927\u304D\u3059\u304E\u308B\u5024: ${issue2.origin ?? "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "ends_with") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "includes") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + if (_issue.format === "regex") + return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + return `\u7121\u52B9\u306A${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`; + case "unrecognized_keys": + return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`; + case "invalid_union": + return "\u7121\u52B9\u306A\u5165\u529B"; + case "invalid_element": + return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`; + default: + return `\u7121\u52B9\u306A\u5165\u529B`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/kh.js + function kh_default() { + return { + localeError: error19() + }; + } + var error19; + var init_kh = __esm({ + "node_modules/zod/v4/locales/kh.js"() { + init_util(); + error19 = () => { + const Sizable = { + string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, + set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)" : "\u179B\u17C1\u1781"; + } + case "object": { + if (Array.isArray(data)) { + return "\u17A2\u17B6\u179A\u17C1 (Array)"; + } + if (data === null) { + return "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", + email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", + url: "URL", + emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", + date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", + time: "\u1798\u17C9\u17C4\u1784 ISO", + duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", + ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", + cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", + base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", + base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", + json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", + e164: "\u179B\u17C1\u1781 E.164", + jwt: "JWT", + template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`; + return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u1792\u17B6\u178F\u17BB"}`; + return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin ?? "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`; + return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`; + case "unrecognized_keys": + return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + case "invalid_union": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + case "invalid_element": + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`; + default: + return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ko.js + function ko_default() { + return { + localeError: error20() + }; + } + var error20; + var init_ko = __esm({ + "node_modules/zod/v4/locales/ko.js"() { + init_util(); + error20 = () => { + const Sizable = { + string: { unit: "\uBB38\uC790", verb: "to have" }, + file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, + array: { unit: "\uAC1C", verb: "to have" }, + set: { unit: "\uAC1C", verb: "to have" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\uC785\uB825", + email: "\uC774\uBA54\uC77C \uC8FC\uC18C", + url: "URL", + emoji: "\uC774\uBAA8\uC9C0", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", + date: "ISO \uB0A0\uC9DC", + time: "ISO \uC2DC\uAC04", + duration: "ISO \uAE30\uAC04", + ipv4: "IPv4 \uC8FC\uC18C", + ipv6: "IPv6 \uC8FC\uC18C", + cidrv4: "IPv4 \uBC94\uC704", + cidrv6: "IPv6 \uBC94\uC704", + base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", + json_string: "JSON \uBB38\uC790\uC5F4", + e164: "E.164 \uBC88\uD638", + jwt: "JWT", + template_literal: "\uC785\uB825" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${parsedType4(issue2.input)}\uC785\uB2C8\uB2E4`; + case "invalid_value": + if (issue2.values.length === 1) + return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "too_big": { + const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC"; + const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC"; + const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4"; + const sizing = getSizing(issue2.origin); + const unit = sizing?.unit ?? "\uC694\uC18C"; + if (sizing) { + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${issue2.origin ?? "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`; + } + if (_issue.format === "ends_with") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "includes") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`; + if (_issue.format === "regex") + return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`; + return `\uC798\uBABB\uB41C ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`; + case "unrecognized_keys": + return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`; + case "invalid_union": + return `\uC798\uBABB\uB41C \uC785\uB825`; + case "invalid_element": + return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`; + default: + return `\uC798\uBABB\uB41C \uC785\uB825`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/mk.js + function mk_default() { + return { + localeError: error21() + }; + } + var error21; + var init_mk = __esm({ + "node_modules/zod/v4/locales/mk.js"() { + init_util(); + error21 = () => { + const Sizable = { + string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, + set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u0431\u0440\u043E\u0458"; + } + case "object": { + if (Array.isArray(data)) { + return "\u043D\u0438\u0437\u0430"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0432\u043D\u0435\u0441", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", + url: "URL", + emoji: "\u0435\u043C\u043E\u045F\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", + date: "ISO \u0434\u0430\u0442\u0443\u043C", + time: "ISO \u0432\u0440\u0435\u043C\u0435", + duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", + cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", + cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", + base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", + json_string: "JSON \u043D\u0438\u0437\u0430", + e164: "E.164 \u0431\u0440\u043E\u0458", + jwt: "JWT", + template_literal: "\u0432\u043D\u0435\u0441" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${parsedType4(issue2.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`; + return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`; + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin ?? "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`; + case "invalid_union": + return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"; + case "invalid_element": + return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`; + default: + return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ms.js + function ms_default() { + return { + localeError: error22() + }; + } + var error22; + var init_ms = __esm({ + "node_modules/zod/v4/locales/ms.js"() { + init_util(); + error22 = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombor"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "input", + email: "alamat e-mel", + 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: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Input tidak sah: dijangka ${issue2.expected}, diterima ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue2.origin ?? "nilai"} adalah ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue2.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue2.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue2.origin}`; + default: + return `Input tidak sah`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/nl.js + function nl_default() { + return { + localeError: error23() + }; + } + var error23; + var init_nl = __esm({ + "node_modules/zod/v4/locales/nl.js"() { + init_util(); + error23 = () => { + const Sizable = { + string: { unit: "tekens" }, + file: { unit: "bytes" }, + array: { unit: "elementen" }, + set: { unit: "elementen" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "getal"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "invoer", + email: "emailadres", + 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 datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Ongeldige invoer: verwacht ${issue2.expected}, ontving ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`; + return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementen"} bevat`; + return `Te lang: verwacht dat ${issue2.origin ?? "waarde"} ${adj}${issue2.maximum.toString()} is`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} bevat`; + } + return `Te kort: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue2.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue2.origin}`; + default: + return `Ongeldige invoer`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/no.js + function no_default() { + return { + localeError: error24() + }; + } + var error24; + var init_no = __esm({ + "node_modules/zod/v4/locales/no.js"() { + init_util(); + error24 = () => { + const Sizable = { + string: { unit: "tegn", verb: "\xE5 ha" }, + file: { unit: "bytes", verb: "\xE5 ha" }, + array: { unit: "elementer", verb: "\xE5 inneholde" }, + set: { unit: "elementer", verb: "\xE5 inneholde" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "tall"; + } + case "object": { + if (Array.isArray(data)) { + return "liste"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "input", + email: "e-postadresse", + 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 dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-omr\xE5de", + ipv6: "IPv6-omr\xE5de", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Ugyldig input: forventet ${issue2.expected}, fikk ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`; + return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue2.origin ?? "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`; + return `Ugyldig ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ugyldig n\xF8kkel i ${issue2.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue2.origin}`; + default: + return `Ugyldig input`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ota.js + function ota_default() { + return { + localeError: error25() + }; + } + var error25; + var init_ota = __esm({ + "node_modules/zod/v4/locales/ota.js"() { + init_util(); + error25 = () => { + const Sizable = { + string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, + file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, + array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, + set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numara"; + } + case "object": { + if (Array.isArray(data)) { + return "saf"; + } + if (data === null) { + return "gayb"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "giren", + email: "epostag\xE2h", + 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 heng\xE2m\u0131", + date: "ISO tarihi", + time: "ISO zaman\u0131", + duration: "ISO m\xFCddeti", + ipv4: "IPv4 ni\u015F\xE2n\u0131", + ipv6: "IPv6 ni\u015F\xE2n\u0131", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-\u015Fifreli metin", + base64url: "base64url-\u015Fifreli metin", + json_string: "JSON metin", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "giren" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `F\xE2sit giren: umulan ${issue2.expected}, al\u0131nan ${parsedType4(issue2.input)}`; + // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`; + return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmal\u0131yd\u0131.`; + return `Fazla b\xFCy\xFCk: ${issue2.origin ?? "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`; + } + return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`; + if (_issue.format === "ends_with") + return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`; + if (_issue.format === "regex") + return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`; + return `F\xE2sit ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`; + case "invalid_union": + return "Giren tan\u0131namad\u0131."; + case "invalid_element": + return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`; + default: + return `K\u0131ymet tan\u0131namad\u0131.`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ps.js + function ps_default() { + return { + localeError: error26() + }; + } + var error26; + var init_ps = __esm({ + "node_modules/zod/v4/locales/ps.js"() { + init_util(); + error26 = () => { + const Sizable = { + string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, + array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, + set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u0639\u062F\u062F"; + } + case "object": { + if (Array.isArray(data)) { + return "\u0627\u0631\u06D0"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0648\u0631\u0648\u062F\u064A", + email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", + date: "\u0646\u06D0\u067C\u0647", + time: "\u0648\u062E\u062A", + duration: "\u0645\u0648\u062F\u0647", + ipv4: "\u062F IPv4 \u067E\u062A\u0647", + ipv6: "\u062F IPv6 \u067E\u062A\u0647", + cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", + cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", + base64: "base64-encoded \u0645\u062A\u0646", + base64url: "base64url-encoded \u0645\u062A\u0646", + json_string: "JSON \u0645\u062A\u0646", + e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", + jwt: "JWT", + template_literal: "\u0648\u0631\u0648\u062F\u064A" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${parsedType4(issue2.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`; + case "invalid_value": + if (issue2.values.length === 1) { + return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`; + } + return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${issue2.origin ?? "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`; + } + return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`; + } + if (_issue.format === "ends_with") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`; + } + if (_issue.format === "includes") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`; + } + if (_issue.format === "regex") { + return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`; + } + return `${Nouns[_issue.format] ?? issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`; + } + case "not_multiple_of": + return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`; + case "unrecognized_keys": + return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + case "invalid_union": + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + case "invalid_element": + return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`; + default: + return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/pl.js + function pl_default() { + return { + localeError: error27() + }; + } + var error27; + var init_pl = __esm({ + "node_modules/zod/v4/locales/pl.js"() { + init_util(); + error27 = () => { + const Sizable = { + string: { unit: "znak\xF3w", verb: "mie\u0107" }, + file: { unit: "bajt\xF3w", verb: "mie\u0107" }, + array: { unit: "element\xF3w", verb: "mie\u0107" }, + set: { unit: "element\xF3w", verb: "mie\u0107" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "liczba"; + } + case "object": { + if (Array.isArray(data)) { + return "tablica"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "wyra\u017Cenie", + email: "adres email", + 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: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", + base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", + json_string: "ci\u0105g znak\xF3w w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wej\u015Bcie" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${issue2.expected}, otrzymano ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`; + return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${sizing.unit ?? "element\xF3w"}`; + } + return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${issue2.origin ?? "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`; + return `Nieprawid\u0142ow(y/a/e) ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Nieprawid\u0142owy klucz w ${issue2.origin}`; + case "invalid_union": + return "Nieprawid\u0142owe dane wej\u015Bciowe"; + case "invalid_element": + return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`; + default: + return `Nieprawid\u0142owe dane wej\u015Bciowe`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/pt.js + function pt_default() { + return { + localeError: error28() + }; + } + var error28; + var init_pt = __esm({ + "node_modules/zod/v4/locales/pt.js"() { + init_util(); + error28 = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "n\xFAmero"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "padr\xE3o", + email: "endere\xE7o de e-mail", + 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: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "dura\xE7\xE3o ISO", + ipv4: "endere\xE7o IPv4", + ipv6: "endere\xE7o IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "n\xFAmero E.164", + jwt: "JWT", + template_literal: "entrada" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Tipo inv\xE1lido: esperado ${issue2.expected}, recebido ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`; + return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Muito grande: esperado que ${issue2.origin ?? "valor"} tivesse ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue2.origin ?? "valor"} fosse ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue2.format} inv\xE1lido`; + } + case "not_multiple_of": + return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`; + case "unrecognized_keys": + return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Chave inv\xE1lida em ${issue2.origin}`; + case "invalid_union": + return "Entrada inv\xE1lida"; + case "invalid_element": + return `Valor inv\xE1lido em ${issue2.origin}`; + default: + return `Campo inv\xE1lido`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ru.js + function getRussianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; + } + function ru_default() { + return { + localeError: error29() + }; + } + var error29; + var init_ru = __esm({ + "node_modules/zod/v4/locales/ru.js"() { + init_util(); + error29 = () => { + const Sizable = { + string: { + unit: { + one: "\u0441\u0438\u043C\u0432\u043E\u043B", + few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", + many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + file: { + unit: { + one: "\u0431\u0430\u0439\u0442", + few: "\u0431\u0430\u0439\u0442\u0430", + many: "\u0431\u0430\u0439\u0442" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + array: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + }, + set: { + unit: { + one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", + few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", + many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" + }, + verb: "\u0438\u043C\u0435\u0442\u044C" + } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E"; + } + case "object": { + if (Array.isArray(data)) { + return "\u043C\u0430\u0441\u0441\u0438\u0432"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0432\u0432\u043E\u0434", + email: "email \u0430\u0434\u0440\u0435\u0441", + url: "URL", + emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", + date: "ISO \u0434\u0430\u0442\u0430", + time: "ISO \u0432\u0440\u0435\u043C\u044F", + duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", + ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", + ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", + cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", + base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", + base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", + json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0432\u043E\u0434" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const maxValue = Number(issue2.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + const minValue = Number(issue2.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`; + } + return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"; + case "invalid_element": + return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`; + default: + return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/sl.js + function sl_default() { + return { + localeError: error30() + }; + } + var error30; + var init_sl = __esm({ + "node_modules/zod/v4/locales/sl.js"() { + init_util(); + error30 = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u0161tevilo"; + } + case "object": { + if (Array.isArray(data)) { + return "tabela"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "vnos", + email: "e-po\u0161tni naslov", + 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 datum in \u010Das", + date: "ISO datum", + time: "ISO \u010Das", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 \u0161tevilka", + jwt: "JWT", + template_literal: "vnos" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Neveljaven vnos: pri\u010Dakovano ${issue2.expected}, prejeto ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`; + return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pri\u010Dakovano, da bo ${issue2.origin ?? "vrednost"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Neveljaven klju\u010D v ${issue2.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue2.origin}`; + default: + return "Neveljaven vnos"; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/sv.js + function sv_default() { + return { + localeError: error31() + }; + } + var error31; + var init_sv = __esm({ + "node_modules/zod/v4/locales/sv.js"() { + init_util(); + error31 = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att inneh\xE5lla" }, + set: { unit: "objekt", verb: "att inneh\xE5lla" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "antal"; + } + case "object": { + if (Array.isArray(data)) { + return "lista"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "regulj\xE4rt uttryck", + email: "e-postadress", + 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-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad str\xE4ng", + base64url: "base64url-kodad str\xE4ng", + json_string: "JSON-str\xE4ng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${issue2.expected}, fick ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`; + return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r stor(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "element"}`; + } + return `F\xF6r stor(t): f\xF6rv\xE4ntat ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `F\xF6r lite(t): f\xF6rv\xE4ntade ${issue2.origin ?? "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`; + return `Ogiltig(t) ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`; + case "unrecognized_keys": + return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue2.origin ?? "v\xE4rdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt v\xE4rde i ${issue2.origin ?? "v\xE4rdet"}`; + default: + return `Ogiltig input`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ta.js + function ta_default() { + return { + localeError: error32() + }; + } + var error32; + var init_ta = __esm({ + "node_modules/zod/v4/locales/ta.js"() { + init_util(); + error32 = () => { + const Sizable = { + string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, + set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1" : "\u0B8E\u0BA3\u0BCD"; + } + case "object": { + if (Array.isArray(data)) { + return "\u0B85\u0BA3\u0BBF"; + } + if (data === null) { + return "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", + email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + 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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", + time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", + duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", + ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", + cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", + base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", + json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", + e164: "E.164 \u0B8E\u0BA3\u0BCD", + jwt: "JWT", + template_literal: "input" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin ?? "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "ends_with") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "includes") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + if (_issue.format === "regex") + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`; + case "unrecognized_keys": + return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`; + case "invalid_union": + return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"; + case "invalid_element": + return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`; + default: + return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/th.js + function th_default() { + return { + localeError: error33() + }; + } + var error33; + var init_th = __esm({ + "node_modules/zod/v4/locales/th.js"() { + init_util(); + error33 = () => { + const Sizable = { + string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, + set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)" : "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02"; + } + case "object": { + if (Array.isArray(data)) { + return "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)"; + } + if (data === null) { + return "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", + email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", + url: "URL", + emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", + time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", + ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", + ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", + cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", + cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", + base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", + base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", + json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", + e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", + jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", + template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`; + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${sizing.unit ?? "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`; + return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin ?? "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`; + if (_issue.format === "regex") + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`; + return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`; + case "unrecognized_keys": + return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + case "invalid_union": + return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49"; + case "invalid_element": + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`; + default: + return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/tr.js + function tr_default() { + return { + localeError: error34() + }; + } + var parsedType3, error34; + var init_tr = __esm({ + "node_modules/zod/v4/locales/tr.js"() { + init_util(); + parsedType3 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + error34 = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmal\u0131" }, + file: { unit: "bayt", verb: "olmal\u0131" }, + array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, + set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "girdi", + email: "e-posta adresi", + 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 tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO s\xFCre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aral\u0131\u011F\u0131", + cidrv6: "IPv6 aral\u0131\u011F\u0131", + base64: "base64 ile \u015Fifrelenmi\u015F metin", + base64url: "base64url ile \u015Fifrelenmi\u015F metin", + json_string: "JSON dizesi", + e164: "E.164 say\u0131s\u0131", + jwt: "JWT", + template_literal: "\u015Eablon dizesi" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `Ge\xE7ersiz de\u011Fer: beklenen ${issue2.expected}, al\u0131nan ${parsedType3(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`; + return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\xF6\u011Fe"}`; + return `\xC7ok b\xFCy\xFCk: beklenen ${issue2.origin ?? "de\u011Fer"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`; + if (_issue.format === "ends_with") + return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`; + if (_issue.format === "regex") + return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`; + return `Ge\xE7ersiz ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`; + case "unrecognized_keys": + return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`; + case "invalid_union": + return "Ge\xE7ersiz de\u011Fer"; + case "invalid_element": + return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`; + default: + return `Ge\xE7ersiz de\u011Fer`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ua.js + function ua_default() { + return { + localeError: error35() + }; + } + var error35; + var init_ua = __esm({ + "node_modules/zod/v4/locales/ua.js"() { + init_util(); + error35 = () => { + const Sizable = { + string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, + set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E"; + } + case "object": { + if (Array.isArray(data)) { + return "\u043C\u0430\u0441\u0438\u0432"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", + email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", + url: "URL", + emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", + date: "\u0434\u0430\u0442\u0430 ISO", + time: "\u0447\u0430\u0441 ISO", + duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", + ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", + ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", + cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", + cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", + base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", + base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", + json_string: "\u0440\u044F\u0434\u043E\u043A JSON", + e164: "\u043D\u043E\u043C\u0435\u0440 E.164", + jwt: "JWT", + template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${parsedType4(issue2.input)}`; + // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`; + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin ?? "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`; + if (_issue.format === "includes") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`; + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`; + case "unrecognized_keys": + return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`; + case "invalid_union": + return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"; + case "invalid_element": + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`; + default: + return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/ur.js + function ur_default() { + return { + localeError: error36() + }; + } + var error36; + var init_ur = __esm({ + "node_modules/zod/v4/locales/ur.js"() { + init_util(); + error36 = () => { + const Sizable = { + string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, + file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, + array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, + set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "\u0646\u0645\u0628\u0631"; + } + case "object": { + if (Array.isArray(data)) { + return "\u0622\u0631\u06D2"; + } + if (data === null) { + return "\u0646\u0644"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0627\u0646 \u067E\u0679", + email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", + url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", + emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", + uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", + uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", + nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", + guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", + ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", + xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", + ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", + datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", + date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", + time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", + duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", + ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", + ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", + cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", + cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", + base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", + json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", + e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", + jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", + template_literal: "\u0627\u0646 \u067E\u0679" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${parsedType4(issue2.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${issue2.origin ?? "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`; + } + return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + } + if (_issue.format === "ends_with") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "includes") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + if (_issue.format === "regex") + return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + return `\u063A\u0644\u0637 ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`; + case "unrecognized_keys": + return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`; + case "invalid_key": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`; + case "invalid_union": + return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"; + case "invalid_element": + return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`; + default: + return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/vi.js + function vi_default() { + return { + localeError: error37() + }; + } + var error37; + var init_vi = __esm({ + "node_modules/zod/v4/locales/vi.js"() { + init_util(); + error37 = () => { + const Sizable = { + string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, + file: { unit: "byte", verb: "c\xF3" }, + array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, + set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "s\u1ED1"; + } + case "object": { + if (Array.isArray(data)) { + return "m\u1EA3ng"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u0111\u1EA7u v\xE0o", + email: "\u0111\u1ECBa ch\u1EC9 email", + 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: "ng\xE0y gi\u1EDD ISO", + date: "ng\xE0y ISO", + time: "gi\u1EDD ISO", + duration: "kho\u1EA3ng th\u1EDDi gian ISO", + ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", + ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", + cidrv4: "d\u1EA3i IPv4", + cidrv6: "d\u1EA3i IPv6", + base64: "chu\u1ED7i m\xE3 h\xF3a base64", + base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", + json_string: "chu\u1ED7i JSON", + e164: "s\u1ED1 E.164", + jwt: "JWT", + template_literal: "\u0111\u1EA7u v\xE0o" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`; + return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "ph\u1EA7n t\u1EED"}`; + return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${issue2.origin ?? "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`; + } + case "not_multiple_of": + return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`; + case "unrecognized_keys": + return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + case "invalid_union": + return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"; + case "invalid_element": + return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`; + default: + return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/zh-CN.js + function zh_CN_default() { + return { + localeError: error38() + }; + } + var error38; + var init_zh_CN = __esm({ + "node_modules/zod/v4/locales/zh-CN.js"() { + init_util(); + error38 = () => { + const Sizable = { + string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, + file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, + array: { unit: "\u9879", verb: "\u5305\u542B" }, + set: { unit: "\u9879", verb: "\u5305\u542B" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "\u975E\u6570\u5B57(NaN)" : "\u6570\u5B57"; + } + case "object": { + if (Array.isArray(data)) { + return "\u6570\u7EC4"; + } + if (data === null) { + return "\u7A7A\u503C(null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u8F93\u5165", + email: "\u7535\u5B50\u90AE\u4EF6", + url: "URL", + emoji: "\u8868\u60C5\u7B26\u53F7", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO\u65E5\u671F\u65F6\u95F4", + date: "ISO\u65E5\u671F", + time: "ISO\u65F6\u95F4", + duration: "ISO\u65F6\u957F", + ipv4: "IPv4\u5730\u5740", + ipv6: "IPv6\u5730\u5740", + cidrv4: "IPv4\u7F51\u6BB5", + cidrv6: "IPv6\u7F51\u6BB5", + base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", + base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", + json_string: "JSON\u5B57\u7B26\u4E32", + e164: "E.164\u53F7\u7801", + jwt: "JWT", + template_literal: "\u8F93\u5165" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`; + return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u4E2A\u5143\u7D20"}`; + return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${issue2.origin ?? "\u503C"} ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`; + if (_issue.format === "ends_with") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`; + if (_issue.format === "includes") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`; + return `\u65E0\u6548${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`; + case "unrecognized_keys": + return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`; + case "invalid_union": + return "\u65E0\u6548\u8F93\u5165"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`; + default: + return `\u65E0\u6548\u8F93\u5165`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/zh-TW.js + function zh_TW_default() { + return { + localeError: error39() + }; + } + var error39; + var init_zh_TW = __esm({ + "node_modules/zod/v4/locales/zh-TW.js"() { + init_util(); + error39 = () => { + const Sizable = { + string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, + file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, + array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, + set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType4 = (data) => { + const t2 = typeof data; + switch (t2) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t2; + }; + const Nouns = { + regex: "\u8F38\u5165", + email: "\u90F5\u4EF6\u5730\u5740", + 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 \u65E5\u671F\u6642\u9593", + date: "ISO \u65E5\u671F", + time: "ISO \u6642\u9593", + duration: "ISO \u671F\u9593", + ipv4: "IPv4 \u4F4D\u5740", + ipv6: "IPv6 \u4F4D\u5740", + cidrv4: "IPv4 \u7BC4\u570D", + cidrv6: "IPv6 \u7BC4\u570D", + base64: "base64 \u7DE8\u78BC\u5B57\u4E32", + base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", + json_string: "JSON \u5B57\u4E32", + e164: "E.164 \u6578\u503C", + jwt: "JWT", + template_literal: "\u8F38\u5165" + }; + return (issue2) => { + switch (issue2.code) { + case "invalid_type": + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${parsedType4(issue2.input)}`; + case "invalid_value": + if (issue2.values.length === 1) + return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`; + return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`; + case "too_big": { + const adj = issue2.inclusive ? "<=" : "<"; + const sizing = getSizing(issue2.origin); + if (sizing) + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${sizing.unit ?? "\u500B\u5143\u7D20"}`; + return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${issue2.origin ?? "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`; + } + case "too_small": { + const adj = issue2.inclusive ? ">=" : ">"; + const sizing = getSizing(issue2.origin); + if (sizing) { + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`; + } + return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue2; + if (_issue.format === "starts_with") { + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`; + } + if (_issue.format === "ends_with") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`; + if (_issue.format === "includes") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`; + if (_issue.format === "regex") + return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`; + return `\u7121\u6548\u7684 ${Nouns[_issue.format] ?? issue2.format}`; + } + case "not_multiple_of": + return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`; + case "unrecognized_keys": + return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`; + case "invalid_key": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`; + case "invalid_union": + return "\u7121\u6548\u7684\u8F38\u5165\u503C"; + case "invalid_element": + return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`; + default: + return `\u7121\u6548\u7684\u8F38\u5165\u503C`; + } + }; + }; + } + }); + + // node_modules/zod/v4/locales/index.js + var locales_exports = {}; + __export(locales_exports, { + ar: () => ar_default, + az: () => az_default, + be: () => be_default, + ca: () => ca_default, + cs: () => cs_default, + de: () => de_default, + en: () => en_default, + eo: () => eo_default, + es: () => es_default, + fa: () => fa_default, + fi: () => fi_default, + fr: () => fr_default, + frCA: () => fr_CA_default, + he: () => he_default, + hu: () => hu_default, + id: () => id_default, + it: () => it_default, + ja: () => ja_default, + kh: () => kh_default, + ko: () => ko_default, + mk: () => mk_default, + ms: () => ms_default, + nl: () => nl_default, + no: () => no_default, + ota: () => ota_default, + pl: () => pl_default, + ps: () => ps_default, + pt: () => pt_default, + ru: () => ru_default, + sl: () => sl_default, + sv: () => sv_default, + ta: () => ta_default, + th: () => th_default, + tr: () => tr_default, + ua: () => ua_default, + ur: () => ur_default, + vi: () => vi_default, + zhCN: () => zh_CN_default, + zhTW: () => zh_TW_default + }); + var init_locales = __esm({ + "node_modules/zod/v4/locales/index.js"() { + init_ar(); + init_az(); + init_be(); + init_ca(); + init_cs(); + init_de(); + init_en(); + init_eo(); + init_es(); + init_fa(); + init_fi(); + init_fr(); + init_fr_CA(); + init_he(); + init_hu(); + init_id(); + init_it(); + init_ja(); + init_kh(); + init_ko(); + init_mk(); + init_ms(); + init_nl(); + init_no(); + init_ota(); + init_ps(); + init_pl(); + init_pt(); + init_ru(); + init_sl(); + init_sv(); + init_ta(); + init_th(); + init_tr(); + init_ua(); + init_ur(); + init_vi(); + init_zh_CN(); + init_zh_TW(); + } + }); + + // node_modules/zod/v4/core/registries.js + function registry() { + return new $ZodRegistry(); + } + var $output, $input, $ZodRegistry, globalRegistry; + var init_registries = __esm({ + "node_modules/zod/v4/core/registries.js"() { + $output = Symbol("ZodOutput"); + $input = Symbol("ZodInput"); + $ZodRegistry = class { + constructor() { + this._map = /* @__PURE__ */ new Map(); + this._idmap = /* @__PURE__ */ new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + if (this._idmap.has(meta.id)) { + throw new Error(`ID ${meta.id} already exists in the registry`); + } + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = /* @__PURE__ */ new Map(); + this._idmap = /* @__PURE__ */ new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + const p2 = schema._zod.parent; + if (p2) { + const pm = { ...this.get(p2) ?? {} }; + delete pm.id; + return { ...pm, ...this._map.get(schema) }; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } + }; + globalRegistry = /* @__PURE__ */ registry(); + } + }); + + // node_modules/zod/v4/core/api.js + function _string(Class2, params) { + return new Class2({ + type: "string", + ...normalizeParams(params) + }); + } + function _coercedString(Class2, params) { + return new Class2({ + type: "string", + coerce: true, + ...normalizeParams(params) + }); + } + function _email(Class2, params) { + return new Class2({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _guid(Class2, params) { + return new Class2({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _uuid(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _uuidv4(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params) + }); + } + function _uuidv6(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params) + }); + } + function _uuidv7(Class2, params) { + return new Class2({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params) + }); + } + function _url(Class2, params) { + return new Class2({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _emoji2(Class2, params) { + return new Class2({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _nanoid(Class2, params) { + return new Class2({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _cuid(Class2, params) { + return new Class2({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _cuid2(Class2, params) { + return new Class2({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _ulid(Class2, params) { + return new Class2({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _xid(Class2, params) { + return new Class2({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _ksuid(Class2, params) { + return new Class2({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _ipv4(Class2, params) { + return new Class2({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _ipv6(Class2, params) { + return new Class2({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _cidrv4(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _cidrv6(Class2, params) { + return new Class2({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _base64(Class2, params) { + return new Class2({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _base64url(Class2, params) { + return new Class2({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _e164(Class2, params) { + return new Class2({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _jwt(Class2, params) { + return new Class2({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params) + }); + } + function _isoDateTime(Class2, params) { + return new Class2({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params) + }); + } + function _isoDate(Class2, params) { + return new Class2({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params) + }); + } + function _isoTime(Class2, params) { + return new Class2({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params) + }); + } + function _isoDuration(Class2, params) { + return new Class2({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params) + }); + } + function _number(Class2, params) { + return new Class2({ + type: "number", + checks: [], + ...normalizeParams(params) + }); + } + function _coercedNumber(Class2, params) { + return new Class2({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params) + }); + } + function _int(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params) + }); + } + function _float32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params) + }); + } + function _float64(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params) + }); + } + function _int32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params) + }); + } + function _uint32(Class2, params) { + return new Class2({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params) + }); + } + function _boolean(Class2, params) { + return new Class2({ + type: "boolean", + ...normalizeParams(params) + }); + } + function _coercedBoolean(Class2, params) { + return new Class2({ + type: "boolean", + coerce: true, + ...normalizeParams(params) + }); + } + function _bigint(Class2, params) { + return new Class2({ + type: "bigint", + ...normalizeParams(params) + }); + } + function _coercedBigint(Class2, params) { + return new Class2({ + type: "bigint", + coerce: true, + ...normalizeParams(params) + }); + } + function _int64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params) + }); + } + function _uint64(Class2, params) { + return new Class2({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params) + }); + } + function _symbol(Class2, params) { + return new Class2({ + type: "symbol", + ...normalizeParams(params) + }); + } + function _undefined2(Class2, params) { + return new Class2({ + type: "undefined", + ...normalizeParams(params) + }); + } + function _null2(Class2, params) { + return new Class2({ + type: "null", + ...normalizeParams(params) + }); + } + function _any(Class2) { + return new Class2({ + type: "any" + }); + } + function _unknown(Class2) { + return new Class2({ + type: "unknown" + }); + } + function _never(Class2, params) { + return new Class2({ + type: "never", + ...normalizeParams(params) + }); + } + function _void(Class2, params) { + return new Class2({ + type: "void", + ...normalizeParams(params) + }); + } + function _date(Class2, params) { + return new Class2({ + type: "date", + ...normalizeParams(params) + }); + } + function _coercedDate(Class2, params) { + return new Class2({ + type: "date", + coerce: true, + ...normalizeParams(params) + }); + } + function _nan(Class2, params) { + return new Class2({ + type: "nan", + ...normalizeParams(params) + }); + } + function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false + }); + } + function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true + }); + } + function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false + }); + } + function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true + }); + } + function _positive(params) { + return _gt(0, params); + } + function _negative(params) { + return _lt(0, params); + } + function _nonpositive(params) { + return _lte(0, params); + } + function _nonnegative(params) { + return _gte(0, params); + } + function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value + }); + } + function _maxSize(maximum, params) { + return new $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum + }); + } + function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum + }); + } + function _size(size, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...normalizeParams(params), + size + }); + } + function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum + }); + return ch; + } + function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum + }); + } + function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length + }); + } + function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern + }); + } + function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params) + }); + } + function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params) + }); + } + function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes + }); + } + function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix + }); + } + function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix + }); + } + function _property(property, schema, params) { + return new $ZodCheckProperty({ + check: "property", + property, + schema, + ...normalizeParams(params) + }); + } + function _mime(types, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...normalizeParams(params) + }); + } + function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx + }); + } + function _normalize(form) { + return _overwrite((input) => input.normalize(form)); + } + function _trim() { + return _overwrite((input) => input.trim()); + } + function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); + } + function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); + } + function _array(Class2, element, params) { + return new Class2({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params) + }); + } + function _union(Class2, options, params) { + return new Class2({ + type: "union", + options, + ...normalizeParams(params) + }); + } + function _discriminatedUnion(Class2, discriminator, options, params) { + return new Class2({ + type: "union", + options, + discriminator, + ...normalizeParams(params) + }); + } + function _intersection(Class2, left, right) { + return new Class2({ + type: "intersection", + left, + right + }); + } + function _tuple(Class2, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class2({ + type: "tuple", + items, + rest, + ...normalizeParams(params) + }); + } + function _record(Class2, keyType, valueType, params) { + return new Class2({ + type: "record", + keyType, + valueType, + ...normalizeParams(params) + }); + } + function _map(Class2, keyType, valueType, params) { + return new Class2({ + type: "map", + keyType, + valueType, + ...normalizeParams(params) + }); + } + function _set(Class2, valueType, params) { + return new Class2({ + type: "set", + valueType, + ...normalizeParams(params) + }); + } + function _enum(Class2, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values; + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); + } + function _nativeEnum(Class2, entries, params) { + return new Class2({ + type: "enum", + entries, + ...normalizeParams(params) + }); + } + function _literal(Class2, value, params) { + return new Class2({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params) + }); + } + function _file(Class2, params) { + return new Class2({ + type: "file", + ...normalizeParams(params) + }); + } + function _transform(Class2, fn) { + return new Class2({ + type: "transform", + transform: fn + }); + } + function _optional(Class2, innerType) { + return new Class2({ + type: "optional", + innerType + }); + } + function _nullable(Class2, innerType) { + return new Class2({ + type: "nullable", + innerType + }); + } + function _default(Class2, innerType, defaultValue) { + return new Class2({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; + } + }); + } + function _nonoptional(Class2, innerType, params) { + return new Class2({ + type: "nonoptional", + innerType, + ...normalizeParams(params) + }); + } + function _success(Class2, innerType) { + return new Class2({ + type: "success", + innerType + }); + } + function _catch(Class2, innerType, catchValue) { + return new Class2({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); + } + function _pipe(Class2, in_, out) { + return new Class2({ + type: "pipe", + in: in_, + out + }); + } + function _readonly(Class2, innerType) { + return new Class2({ + type: "readonly", + innerType + }); + } + function _templateLiteral(Class2, parts, params) { + return new Class2({ + type: "template_literal", + parts, + ...normalizeParams(params) + }); + } + function _lazy(Class2, getter) { + return new Class2({ + type: "lazy", + getter + }); + } + function _promise(Class2, innerType) { + return new Class2({ + type: "promise", + innerType + }); + } + function _custom(Class2, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...norm + }); + return schema; + } + function _refine(Class2, fn, _params) { + const schema = new Class2({ + type: "custom", + check: "custom", + fn, + ...normalizeParams(_params) + }); + return schema; + } + function _stringbool(Classes, _params) { + const params = normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v2) => typeof v2 === "string" ? v2.toLowerCase() : v2); + falsyArray = falsyArray.map((v2) => typeof v2 === "string" ? v2.toLowerCase() : v2); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Pipe = Classes.Pipe ?? $ZodPipe; + const _Boolean = Classes.Boolean ?? $ZodBoolean; + const _String = Classes.String ?? $ZodString; + const _Transform = Classes.Transform ?? $ZodTransform; + const tx = new _Transform({ + type: "transform", + transform: (input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } else if (falsySet.has(data)) { + return false; + } else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: tx + }); + return {}; + } + }, + error: params.error + }); + const innerPipe = new _Pipe({ + type: "pipe", + in: new _String({ type: "string", error: params.error }), + out: tx, + error: params.error + }); + const outerPipe = new _Pipe({ + type: "pipe", + in: innerPipe, + out: new _Boolean({ + type: "boolean", + error: params.error + }), + error: params.error + }); + return outerPipe; + } + function _stringFormat(Class2, format, fnOrRegex, _params = {}) { + const params = normalizeParams(_params); + const def = { + ...normalizeParams(_params), + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class2(def); + return inst; + } + var TimePrecision; + var init_api = __esm({ + "node_modules/zod/v4/core/api.js"() { + init_checks(); + init_schemas(); + init_util(); + TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6 + }; + } + }); + + // node_modules/zod/v4/core/function.js + function _function(params) { + return new $ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? _tuple($ZodTuple, params?.input) : params?.input ?? _array($ZodArray, _unknown($ZodUnknown)), + output: params?.output ?? _unknown($ZodUnknown) + }); + } + var $ZodFunction; + var init_function = __esm({ + "node_modules/zod/v4/core/function.js"() { + init_api(); + init_parse(); + init_schemas(); + init_schemas(); + $ZodFunction = class { + constructor(def) { + this._def = def; + this.def = def; + } + implement(func) { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + const impl = (...args) => { + const parsedArgs = this._def.input ? parse(this._def.input, args, void 0, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = func(...parsedArgs); + return this._def.output ? parse(this._def.output, output, void 0, { callee: impl }) : output; + }; + return impl; + } + implementAsync(func) { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + const impl = async (...args) => { + const parsedArgs = this._def.input ? await parseAsync(this._def.input, args, void 0, { callee: impl }) : args; + if (!Array.isArray(parsedArgs)) { + throw new Error("Invalid arguments schema: not an array or tuple schema."); + } + const output = await func(...parsedArgs); + return this._def.output ? parseAsync(this._def.output, output, void 0, { callee: impl }) : output; + }; + return impl; + } + input(...args) { + const F2 = this.constructor; + if (Array.isArray(args[0])) { + return new F2({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1] + }), + output: this._def.output + }); + } + return new F2({ + type: "function", + input: args[0], + output: this._def.output + }); + } + output(output) { + const F2 = this.constructor; + return new F2({ + type: "function", + input: this._def.input, + output + }); + } + }; + } + }); + + // node_modules/zod/v4/core/to-json-schema.js + function toJSONSchema(input, _params) { + if (input instanceof $ZodRegistry) { + const gen2 = new JSONSchemaGenerator(_params); + const defs = {}; + for (const entry of input._idmap.entries()) { + const [_2, schema] = entry; + gen2.process(schema); + } + const schemas = {}; + const external = { + registry: input, + uri: _params?.uri, + defs + }; + for (const entry of input._idmap.entries()) { + const [key, schema] = entry; + schemas[key] = gen2.emit(schema, { + ..._params, + external + }); + } + if (Object.keys(defs).length > 0) { + const defsSegment = gen2.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs + }; + } + return { schemas }; + } + const gen = new JSONSchemaGenerator(_params); + gen.process(input); + return gen.emit(input, _params); + } + function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const schema = _schema; + const def = schema._zod.def; + switch (def.type) { + case "string": + case "number": + case "bigint": + case "boolean": + case "date": + case "symbol": + case "undefined": + case "null": + case "any": + case "unknown": + case "never": + case "void": + case "literal": + case "enum": + case "nan": + case "file": + case "template_literal": + return false; + case "array": { + return isTransforming(def.element, ctx); + } + case "object": { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + case "union": { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + case "intersection": { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + case "tuple": { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + case "record": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + case "map": { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + case "set": { + return isTransforming(def.valueType, ctx); + } + // inner types + case "promise": + case "optional": + case "nonoptional": + case "nullable": + case "readonly": + return isTransforming(def.innerType, ctx); + case "lazy": + return isTransforming(def.getter(), ctx); + case "default": { + return isTransforming(def.innerType, ctx); + } + case "prefault": { + return isTransforming(def.innerType, ctx); + } + case "custom": { + return false; + } + case "transform": { + return true; + } + case "pipe": { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + case "success": { + return false; + } + case "catch": { + return false; + } + default: + def; + } + throw new Error(`Unknown schema type: ${def.type}`); + } + var JSONSchemaGenerator; + var init_to_json_schema = __esm({ + "node_modules/zod/v4/core/to-json-schema.js"() { + init_registries(); + init_util(); + JSONSchemaGenerator = class { + constructor(params) { + this.counter = 0; + this.metadataRegistry = params?.metadata ?? globalRegistry; + this.target = params?.target ?? "draft-2020-12"; + this.unrepresentable = params?.unrepresentable ?? "throw"; + this.override = params?.override ?? (() => { + }); + this.io = params?.io ?? "output"; + this.seen = /* @__PURE__ */ new Map(); + } + process(schema, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "" + // do not set + }; + const seen = this.seen.get(schema); + if (seen) { + seen.count++; + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + const result = { schema: {}, count: 1, cycle: void 0, path: _params.path }; + this.seen.set(schema, result); + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path + }; + const parent = schema._zod.parent; + if (parent) { + result.ref = parent; + this.process(parent, params); + this.seen.get(parent).isParent = true; + } else { + const _json = result.schema; + switch (def.type) { + case "string": { + const json2 = _json; + json2.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag; + if (typeof minimum === "number") + json2.minLength = minimum; + if (typeof maximum === "number") + json2.maxLength = maximum; + if (format) { + json2.format = formatMap[format] ?? format; + if (json2.format === "") + delete json2.format; + } + if (contentEncoding) + json2.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json2.pattern = regexes[0].source; + else if (regexes.length > 1) { + result.schema.allOf = [ + ...regexes.map((regex) => ({ + ...this.target === "draft-7" ? { type: "string" } : {}, + pattern: regex.source + })) + ]; + } + } + break; + } + case "number": { + const json2 = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json2.type = "integer"; + else + json2.type = "number"; + if (typeof exclusiveMinimum === "number") + json2.exclusiveMinimum = exclusiveMinimum; + if (typeof minimum === "number") { + json2.minimum = minimum; + if (typeof exclusiveMinimum === "number") { + if (exclusiveMinimum >= minimum) + delete json2.minimum; + else + delete json2.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") + json2.exclusiveMaximum = exclusiveMaximum; + if (typeof maximum === "number") { + json2.maximum = maximum; + if (typeof exclusiveMaximum === "number") { + if (exclusiveMaximum <= maximum) + delete json2.maximum; + else + delete json2.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json2.multipleOf = multipleOf; + break; + } + case "boolean": { + const json2 = _json; + json2.type = "boolean"; + break; + } + case "bigint": { + if (this.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } + break; + } + case "symbol": { + if (this.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } + break; + } + case "null": { + _json.type = "null"; + break; + } + case "any": { + break; + } + case "unknown": { + break; + } + case "undefined": { + if (this.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } + break; + } + case "void": { + if (this.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } + break; + } + case "never": { + _json.not = {}; + break; + } + case "date": { + if (this.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } + break; + } + case "array": { + const json2 = _json; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + json2.type = "array"; + json2.items = this.process(def.element, { ...params, path: [...params.path, "items"] }); + break; + } + case "object": { + const json2 = _json; + json2.type = "object"; + json2.properties = {}; + const shape = def.shape; + for (const key in shape) { + json2.properties[key] = this.process(shape[key], { + ...params, + path: [...params.path, "properties", key] + }); + } + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v2 = def.shape[key]._zod; + if (this.io === "input") { + return v2.optin === void 0; + } else { + return v2.optout === void 0; + } + })); + if (requiredKeys.size > 0) { + json2.required = Array.from(requiredKeys); + } + if (def.catchall?._zod.def.type === "never") { + json2.additionalProperties = false; + } else if (!def.catchall) { + if (this.io === "output") + json2.additionalProperties = false; + } else if (def.catchall) { + json2.additionalProperties = this.process(def.catchall, { + ...params, + path: [...params.path, "additionalProperties"] + }); + } + break; + } + case "union": { + const json2 = _json; + json2.anyOf = def.options.map((x, i2) => this.process(x, { + ...params, + path: [...params.path, "anyOf", i2] + })); + break; + } + case "intersection": { + const json2 = _json; + const a = this.process(def.left, { + ...params, + path: [...params.path, "allOf", 0] + }); + const b2 = this.process(def.right, { + ...params, + path: [...params.path, "allOf", 1] + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...isSimpleIntersection(a) ? a.allOf : [a], + ...isSimpleIntersection(b2) ? b2.allOf : [b2] + ]; + json2.allOf = allOf; + break; + } + case "tuple": { + const json2 = _json; + json2.type = "array"; + const prefixItems = def.items.map((x, i2) => this.process(x, { ...params, path: [...params.path, "prefixItems", i2] })); + if (this.target === "draft-2020-12") { + json2.prefixItems = prefixItems; + } else { + json2.items = prefixItems; + } + if (def.rest) { + const rest = this.process(def.rest, { + ...params, + path: [...params.path, "items"] + }); + if (this.target === "draft-2020-12") { + json2.items = rest; + } else { + json2.additionalItems = rest; + } + } + if (def.rest) { + json2.items = this.process(def.rest, { + ...params, + path: [...params.path, "items"] + }); + } + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json2.minItems = minimum; + if (typeof maximum === "number") + json2.maxItems = maximum; + break; + } + case "record": { + const json2 = _json; + json2.type = "object"; + json2.propertyNames = this.process(def.keyType, { ...params, path: [...params.path, "propertyNames"] }); + json2.additionalProperties = this.process(def.valueType, { + ...params, + path: [...params.path, "additionalProperties"] + }); + break; + } + case "map": { + if (this.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } + break; + } + case "set": { + if (this.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } + break; + } + case "enum": { + const json2 = _json; + const values = getEnumValues(def.entries); + if (values.every((v2) => typeof v2 === "number")) + json2.type = "number"; + if (values.every((v2) => typeof v2 === "string")) + json2.type = "string"; + json2.enum = values; + break; + } + case "literal": { + const json2 = _json; + const vals = []; + for (const val of def.values) { + if (val === void 0) { + if (this.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } else { + } + } else if (typeof val === "bigint") { + if (this.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } else { + vals.push(Number(val)); + } + } else { + vals.push(val); + } + } + if (vals.length === 0) { + } else if (vals.length === 1) { + const val = vals[0]; + json2.type = val === null ? "null" : typeof val; + json2.const = val; + } else { + if (vals.every((v2) => typeof v2 === "number")) + json2.type = "number"; + if (vals.every((v2) => typeof v2 === "string")) + json2.type = "string"; + if (vals.every((v2) => typeof v2 === "boolean")) + json2.type = "string"; + if (vals.every((v2) => v2 === null)) + json2.type = "null"; + json2.enum = vals; + } + break; + } + case "file": { + const json2 = _json; + const file2 = { + type: "string", + format: "binary", + contentEncoding: "binary" + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== void 0) + file2.minLength = minimum; + if (maximum !== void 0) + file2.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file2.contentMediaType = mime[0]; + Object.assign(json2, file2); + } else { + json2.anyOf = mime.map((m) => { + const mFile = { ...file2, contentMediaType: m }; + return mFile; + }); + } + } else { + Object.assign(json2, file2); + } + break; + } + case "transform": { + if (this.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } + break; + } + case "nullable": { + const inner = this.process(def.innerType, params); + _json.anyOf = [inner, { type: "null" }]; + break; + } + case "nonoptional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "success": { + const json2 = _json; + json2.type = "boolean"; + break; + } + case "default": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.default = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "prefault": { + this.process(def.innerType, params); + result.ref = def.innerType; + if (this.io === "input") + _json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); + break; + } + case "catch": { + this.process(def.innerType, params); + result.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(void 0); + } catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + _json.default = catchValue; + break; + } + case "nan": { + if (this.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } + break; + } + case "template_literal": { + const json2 = _json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + json2.type = "string"; + json2.pattern = pattern.source; + break; + } + case "pipe": { + const innerType = this.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "readonly": { + this.process(def.innerType, params); + result.ref = def.innerType; + _json.readOnly = true; + break; + } + // passthrough types + case "promise": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "optional": { + this.process(def.innerType, params); + result.ref = def.innerType; + break; + } + case "lazy": { + const innerType = schema._zod.innerType; + this.process(innerType, params); + result.ref = innerType; + break; + } + case "custom": { + if (this.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } + break; + } + default: { + def; + } + } + } + } + const meta = this.metadataRegistry.get(schema); + if (meta) + Object.assign(result.schema, meta); + if (this.io === "input" && isTransforming(schema)) { + delete result.schema.examples; + delete result.schema.default; + } + if (this.io === "input" && result.schema._prefault) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + const _result = this.seen.get(schema); + return _result.schema; + } + emit(schema, _params) { + const params = { + cycles: _params?.cycles ?? "ref", + reused: _params?.reused ?? "inline", + // unrepresentable: _params?.unrepresentable ?? "throw", + // uri: _params?.uri ?? ((id) => `${id}`), + external: _params?.external ?? void 0 + }; + const root2 = this.seen.get(schema); + if (!root2) + throw new Error("Unprocessed schema. This is a bug in Zod."); + const makeURI = (entry) => { + const defsSegment = this.target === "draft-2020-12" ? "$defs" : "definitions"; + if (params.external) { + const externalId = params.external.registry.get(entry[0])?.id; + const uriGenerator = params.external.uri ?? ((id2) => id2); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${this.counter++}`; + entry[1].defId = id; + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root2) { + return { ref: "#" }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${this.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + const extractToDef = (entry) => { + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + if (defId) + seen.defId = defId; + const schema2 = seen.schema; + for (const key in schema2) { + delete schema2[key]; + } + schema2.$ref = ref; + }; + if (params.cycles === "throw") { + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`); + } + } + } + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (schema === entry[0]) { + extractToDef(entry); + continue; + } + if (params.external) { + const ext = params.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + const id = this.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + if (seen.cycle) { + extractToDef(entry); + continue; + } + if (seen.count > 1) { + if (params.reused === "ref") { + extractToDef(entry); + continue; + } + } + } + const flattenRef = (zodSchema, params2) => { + const seen = this.seen.get(zodSchema); + const schema2 = seen.def ?? seen.schema; + const _cached = { ...schema2 }; + if (seen.ref === null) { + return; + } + const ref = seen.ref; + seen.ref = null; + if (ref) { + flattenRef(ref, params2); + const refSchema = this.seen.get(ref).schema; + if (refSchema.$ref && params2.target === "draft-7") { + schema2.allOf = schema2.allOf ?? []; + schema2.allOf.push(refSchema); + } else { + Object.assign(schema2, refSchema); + Object.assign(schema2, _cached); + } + } + if (!seen.isParent) + this.override({ + zodSchema, + jsonSchema: schema2, + path: seen.path ?? [] + }); + }; + for (const entry of [...this.seen.entries()].reverse()) { + flattenRef(entry[0], { target: this.target }); + } + const result = {}; + if (this.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } else if (this.target === "draft-7") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } else { + console.warn(`Invalid target: ${this.target}`); + } + if (params.external?.uri) { + const id = params.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = params.external.uri(id); + } + Object.assign(result, root2.def); + const defs = params.external?.defs ?? {}; + for (const entry of this.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } + } + if (params.external) { + } else { + if (Object.keys(defs).length > 0) { + if (this.target === "draft-2020-12") { + result.$defs = defs; + } else { + result.definitions = defs; + } + } + } + try { + return JSON.parse(JSON.stringify(result)); + } catch (_err) { + throw new Error("Error converting schema to JSON."); + } + } + }; + } + }); + + // node_modules/zod/v4/core/json-schema.js + var json_schema_exports = {}; + var init_json_schema = __esm({ + "node_modules/zod/v4/core/json-schema.js"() { + } + }); + + // node_modules/zod/v4/core/index.js + var core_exports2 = {}; + __export(core_exports2, { + $ZodAny: () => $ZodAny, + $ZodArray: () => $ZodArray, + $ZodAsyncError: () => $ZodAsyncError, + $ZodBase64: () => $ZodBase64, + $ZodBase64URL: () => $ZodBase64URL, + $ZodBigInt: () => $ZodBigInt, + $ZodBigIntFormat: () => $ZodBigIntFormat, + $ZodBoolean: () => $ZodBoolean, + $ZodCIDRv4: () => $ZodCIDRv4, + $ZodCIDRv6: () => $ZodCIDRv6, + $ZodCUID: () => $ZodCUID, + $ZodCUID2: () => $ZodCUID2, + $ZodCatch: () => $ZodCatch, + $ZodCheck: () => $ZodCheck, + $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat, + $ZodCheckEndsWith: () => $ZodCheckEndsWith, + $ZodCheckGreaterThan: () => $ZodCheckGreaterThan, + $ZodCheckIncludes: () => $ZodCheckIncludes, + $ZodCheckLengthEquals: () => $ZodCheckLengthEquals, + $ZodCheckLessThan: () => $ZodCheckLessThan, + $ZodCheckLowerCase: () => $ZodCheckLowerCase, + $ZodCheckMaxLength: () => $ZodCheckMaxLength, + $ZodCheckMaxSize: () => $ZodCheckMaxSize, + $ZodCheckMimeType: () => $ZodCheckMimeType, + $ZodCheckMinLength: () => $ZodCheckMinLength, + $ZodCheckMinSize: () => $ZodCheckMinSize, + $ZodCheckMultipleOf: () => $ZodCheckMultipleOf, + $ZodCheckNumberFormat: () => $ZodCheckNumberFormat, + $ZodCheckOverwrite: () => $ZodCheckOverwrite, + $ZodCheckProperty: () => $ZodCheckProperty, + $ZodCheckRegex: () => $ZodCheckRegex, + $ZodCheckSizeEquals: () => $ZodCheckSizeEquals, + $ZodCheckStartsWith: () => $ZodCheckStartsWith, + $ZodCheckStringFormat: () => $ZodCheckStringFormat, + $ZodCheckUpperCase: () => $ZodCheckUpperCase, + $ZodCustom: () => $ZodCustom, + $ZodCustomStringFormat: () => $ZodCustomStringFormat, + $ZodDate: () => $ZodDate, + $ZodDefault: () => $ZodDefault, + $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion, + $ZodE164: () => $ZodE164, + $ZodEmail: () => $ZodEmail, + $ZodEmoji: () => $ZodEmoji, + $ZodEnum: () => $ZodEnum, + $ZodError: () => $ZodError, + $ZodFile: () => $ZodFile, + $ZodFunction: () => $ZodFunction, + $ZodGUID: () => $ZodGUID, + $ZodIPv4: () => $ZodIPv4, + $ZodIPv6: () => $ZodIPv6, + $ZodISODate: () => $ZodISODate, + $ZodISODateTime: () => $ZodISODateTime, + $ZodISODuration: () => $ZodISODuration, + $ZodISOTime: () => $ZodISOTime, + $ZodIntersection: () => $ZodIntersection, + $ZodJWT: () => $ZodJWT, + $ZodKSUID: () => $ZodKSUID, + $ZodLazy: () => $ZodLazy, + $ZodLiteral: () => $ZodLiteral, + $ZodMap: () => $ZodMap, + $ZodNaN: () => $ZodNaN, + $ZodNanoID: () => $ZodNanoID, + $ZodNever: () => $ZodNever, + $ZodNonOptional: () => $ZodNonOptional, + $ZodNull: () => $ZodNull, + $ZodNullable: () => $ZodNullable, + $ZodNumber: () => $ZodNumber, + $ZodNumberFormat: () => $ZodNumberFormat, + $ZodObject: () => $ZodObject, + $ZodOptional: () => $ZodOptional, + $ZodPipe: () => $ZodPipe, + $ZodPrefault: () => $ZodPrefault, + $ZodPromise: () => $ZodPromise, + $ZodReadonly: () => $ZodReadonly, + $ZodRealError: () => $ZodRealError, + $ZodRecord: () => $ZodRecord, + $ZodRegistry: () => $ZodRegistry, + $ZodSet: () => $ZodSet, + $ZodString: () => $ZodString, + $ZodStringFormat: () => $ZodStringFormat, + $ZodSuccess: () => $ZodSuccess, + $ZodSymbol: () => $ZodSymbol, + $ZodTemplateLiteral: () => $ZodTemplateLiteral, + $ZodTransform: () => $ZodTransform, + $ZodTuple: () => $ZodTuple, + $ZodType: () => $ZodType, + $ZodULID: () => $ZodULID, + $ZodURL: () => $ZodURL, + $ZodUUID: () => $ZodUUID, + $ZodUndefined: () => $ZodUndefined, + $ZodUnion: () => $ZodUnion, + $ZodUnknown: () => $ZodUnknown, + $ZodVoid: () => $ZodVoid, + $ZodXID: () => $ZodXID, + $brand: () => $brand, + $constructor: () => $constructor, + $input: () => $input, + $output: () => $output, + Doc: () => Doc, + JSONSchema: () => json_schema_exports, + JSONSchemaGenerator: () => JSONSchemaGenerator, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + _any: () => _any, + _array: () => _array, + _base64: () => _base64, + _base64url: () => _base64url, + _bigint: () => _bigint, + _boolean: () => _boolean, + _catch: () => _catch, + _cidrv4: () => _cidrv4, + _cidrv6: () => _cidrv6, + _coercedBigint: () => _coercedBigint, + _coercedBoolean: () => _coercedBoolean, + _coercedDate: () => _coercedDate, + _coercedNumber: () => _coercedNumber, + _coercedString: () => _coercedString, + _cuid: () => _cuid, + _cuid2: () => _cuid2, + _custom: () => _custom, + _date: () => _date, + _default: () => _default, + _discriminatedUnion: () => _discriminatedUnion, + _e164: () => _e164, + _email: () => _email, + _emoji: () => _emoji2, + _endsWith: () => _endsWith, + _enum: () => _enum, + _file: () => _file, + _float32: () => _float32, + _float64: () => _float64, + _gt: () => _gt, + _gte: () => _gte, + _guid: () => _guid, + _includes: () => _includes, + _int: () => _int, + _int32: () => _int32, + _int64: () => _int64, + _intersection: () => _intersection, + _ipv4: () => _ipv4, + _ipv6: () => _ipv6, + _isoDate: () => _isoDate, + _isoDateTime: () => _isoDateTime, + _isoDuration: () => _isoDuration, + _isoTime: () => _isoTime, + _jwt: () => _jwt, + _ksuid: () => _ksuid, + _lazy: () => _lazy, + _length: () => _length, + _literal: () => _literal, + _lowercase: () => _lowercase, + _lt: () => _lt, + _lte: () => _lte, + _map: () => _map, + _max: () => _lte, + _maxLength: () => _maxLength, + _maxSize: () => _maxSize, + _mime: () => _mime, + _min: () => _gte, + _minLength: () => _minLength, + _minSize: () => _minSize, + _multipleOf: () => _multipleOf, + _nan: () => _nan, + _nanoid: () => _nanoid, + _nativeEnum: () => _nativeEnum, + _negative: () => _negative, + _never: () => _never, + _nonnegative: () => _nonnegative, + _nonoptional: () => _nonoptional, + _nonpositive: () => _nonpositive, + _normalize: () => _normalize, + _null: () => _null2, + _nullable: () => _nullable, + _number: () => _number, + _optional: () => _optional, + _overwrite: () => _overwrite, + _parse: () => _parse, + _parseAsync: () => _parseAsync, + _pipe: () => _pipe, + _positive: () => _positive, + _promise: () => _promise, + _property: () => _property, + _readonly: () => _readonly, + _record: () => _record, + _refine: () => _refine, + _regex: () => _regex, + _safeParse: () => _safeParse, + _safeParseAsync: () => _safeParseAsync, + _set: () => _set, + _size: () => _size, + _startsWith: () => _startsWith, + _string: () => _string, + _stringFormat: () => _stringFormat, + _stringbool: () => _stringbool, + _success: () => _success, + _symbol: () => _symbol, + _templateLiteral: () => _templateLiteral, + _toLowerCase: () => _toLowerCase, + _toUpperCase: () => _toUpperCase, + _transform: () => _transform, + _trim: () => _trim, + _tuple: () => _tuple, + _uint32: () => _uint32, + _uint64: () => _uint64, + _ulid: () => _ulid, + _undefined: () => _undefined2, + _union: () => _union, + _unknown: () => _unknown, + _uppercase: () => _uppercase, + _url: () => _url, + _uuid: () => _uuid, + _uuidv4: () => _uuidv4, + _uuidv6: () => _uuidv6, + _uuidv7: () => _uuidv7, + _void: () => _void, + _xid: () => _xid, + clone: () => clone, + config: () => config, + flattenError: () => flattenError, + formatError: () => formatError, + function: () => _function, + globalConfig: () => globalConfig, + globalRegistry: () => globalRegistry, + isValidBase64: () => isValidBase64, + isValidBase64URL: () => isValidBase64URL, + isValidJWT: () => isValidJWT, + locales: () => locales_exports, + parse: () => parse, + parseAsync: () => parseAsync, + prettifyError: () => prettifyError, + regexes: () => regexes_exports, + registry: () => registry, + safeParse: () => safeParse, + safeParseAsync: () => safeParseAsync, + toDotPath: () => toDotPath, + toJSONSchema: () => toJSONSchema, + treeifyError: () => treeifyError, + util: () => util_exports, + version: () => version + }); + var init_core2 = __esm({ + "node_modules/zod/v4/core/index.js"() { + init_core(); + init_parse(); + init_errors(); + init_schemas(); + init_checks(); + init_versions(); + init_util(); + init_regexes(); + init_locales(); + init_registries(); + init_doc(); + init_function(); + init_api(); + init_to_json_schema(); + init_json_schema(); + } + }); + + // node_modules/zod/v4/classic/checks.js + var init_checks2 = __esm({ + "node_modules/zod/v4/classic/checks.js"() { + init_core2(); + } + }); + + // node_modules/zod/v4/classic/iso.js + var iso_exports = {}; + __export(iso_exports, { + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + date: () => date2, + datetime: () => datetime2, + duration: () => duration2, + time: () => time2 + }); + function datetime2(params) { + return _isoDateTime(ZodISODateTime, params); + } + function date2(params) { + return _isoDate(ZodISODate, params); + } + function time2(params) { + return _isoTime(ZodISOTime, params); + } + function duration2(params) { + return _isoDuration(ZodISODuration, params); + } + var ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration; + var init_iso = __esm({ + "node_modules/zod/v4/classic/iso.js"() { + init_core2(); + init_schemas2(); + ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); + }); + } + }); + + // node_modules/zod/v4/classic/errors.js + var initializer2, ZodError, ZodRealError; + var init_errors2 = __esm({ + "node_modules/zod/v4/classic/errors.js"() { + init_core2(); + init_core2(); + initializer2 = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper) + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper) + // enumerable: false, + }, + addIssue: { + value: (issue2) => inst.issues.push(issue2) + // enumerable: false, + }, + addIssues: { + value: (issues2) => inst.issues.push(...issues2) + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + } + // enumerable: false, + } + }); + }; + ZodError = $constructor("ZodError", initializer2); + ZodRealError = $constructor("ZodError", initializer2, { + Parent: Error + }); + } + }); + + // node_modules/zod/v4/classic/parse.js + var parse2, parseAsync2, safeParse3, safeParseAsync2; + var init_parse2 = __esm({ + "node_modules/zod/v4/classic/parse.js"() { + init_core2(); + init_errors2(); + parse2 = /* @__PURE__ */ _parse(ZodRealError); + parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError); + safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError); + safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError); + } + }); + + // node_modules/zod/v4/classic/schemas.js + function string2(params) { + return _string(ZodString, params); + } + function email2(params) { + return _email(ZodEmail, params); + } + function guid2(params) { + return _guid(ZodGUID, params); + } + function uuid2(params) { + return _uuid(ZodUUID, params); + } + function uuidv4(params) { + return _uuidv4(ZodUUID, params); + } + function uuidv6(params) { + return _uuidv6(ZodUUID, params); + } + function uuidv7(params) { + return _uuidv7(ZodUUID, params); + } + function url(params) { + return _url(ZodURL, params); + } + function emoji2(params) { + return _emoji2(ZodEmoji, params); + } + function nanoid2(params) { + return _nanoid(ZodNanoID, params); + } + function cuid3(params) { + return _cuid(ZodCUID, params); + } + function cuid22(params) { + return _cuid2(ZodCUID2, params); + } + function ulid2(params) { + return _ulid(ZodULID, params); + } + function xid2(params) { + return _xid(ZodXID, params); + } + function ksuid2(params) { + return _ksuid(ZodKSUID, params); + } + function ipv42(params) { + return _ipv4(ZodIPv4, params); + } + function ipv62(params) { + return _ipv6(ZodIPv6, params); + } + function cidrv42(params) { + return _cidrv4(ZodCIDRv4, params); + } + function cidrv62(params) { + return _cidrv6(ZodCIDRv6, params); + } + function base642(params) { + return _base64(ZodBase64, params); + } + function base64url2(params) { + return _base64url(ZodBase64URL, params); + } + function e1642(params) { + return _e164(ZodE164, params); + } + function jwt(params) { + return _jwt(ZodJWT, params); + } + function stringFormat(format, fnOrRegex, _params = {}) { + return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); + } + function number2(params) { + return _number(ZodNumber, params); + } + function int(params) { + return _int(ZodNumberFormat, params); + } + function float32(params) { + return _float32(ZodNumberFormat, params); + } + function float64(params) { + return _float64(ZodNumberFormat, params); + } + function int32(params) { + return _int32(ZodNumberFormat, params); + } + function uint32(params) { + return _uint32(ZodNumberFormat, params); + } + function boolean2(params) { + return _boolean(ZodBoolean, params); + } + function bigint2(params) { + return _bigint(ZodBigInt, params); + } + function int64(params) { + return _int64(ZodBigIntFormat, params); + } + function uint64(params) { + return _uint64(ZodBigIntFormat, params); + } + function symbol(params) { + return _symbol(ZodSymbol, params); + } + function _undefined3(params) { + return _undefined2(ZodUndefined, params); + } + function _null3(params) { + return _null2(ZodNull, params); + } + function any() { + return _any(ZodAny); + } + function unknown() { + return _unknown(ZodUnknown); + } + function never(params) { + return _never(ZodNever, params); + } + function _void2(params) { + return _void(ZodVoid, params); + } + function date3(params) { + return _date(ZodDate, params); + } + function array(element, params) { + return _array(ZodArray, element, params); + } + function keyof(schema) { + const shape = schema._zod.def.shape; + return literal(Object.keys(shape)); + } + function object2(shape, params) { + const def = { + type: "object", + get shape() { + util_exports.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + ...util_exports.normalizeParams(params) + }; + return new ZodObject(def); + } + function strictObject(shape, params) { + return new ZodObject({ + type: "object", + get shape() { + util_exports.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: never(), + ...util_exports.normalizeParams(params) + }); + } + function looseObject(shape, params) { + return new ZodObject({ + type: "object", + get shape() { + util_exports.assignProp(this, "shape", { ...shape }); + return this.shape; + }, + catchall: unknown(), + ...util_exports.normalizeParams(params) + }); + } + function union(options, params) { + return new ZodUnion({ + type: "union", + options, + ...util_exports.normalizeParams(params) + }); + } + function discriminatedUnion(discriminator, options, params) { + return new ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, + ...util_exports.normalizeParams(params) + }); + } + function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left, + right + }); + } + function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items, + rest, + ...util_exports.normalizeParams(params) + }); + } + function record(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); + } + function partialRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType: union([keyType, never()]), + valueType, + ...util_exports.normalizeParams(params) + }); + } + function map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType, + valueType, + ...util_exports.normalizeParams(params) + }); + } + function set(valueType, params) { + return new ZodSet({ + type: "set", + valueType, + ...util_exports.normalizeParams(params) + }); + } + function _enum2(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); + } + function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util_exports.normalizeParams(params) + }); + } + function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util_exports.normalizeParams(params) + }); + } + function file(params) { + return _file(ZodFile, params); + } + function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn + }); + } + function optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType + }); + } + function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType + }); + } + function nullish2(innerType) { + return optional(nullable(innerType)); + } + function _default2(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; + } + }); + } + function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : defaultValue; + } + }); + } + function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType, + ...util_exports.normalizeParams(params) + }); + } + function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType + }); + } + function _catch2(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType, + catchValue: typeof catchValue === "function" ? catchValue : () => catchValue + }); + } + function nan(params) { + return _nan(ZodNaN, params); + } + function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out + // ...util.normalizeParams(params), + }); + } + function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType + }); + } + function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util_exports.normalizeParams(params) + }); + } + function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter + }); + } + function promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType + }); + } + function check(fn) { + const ch = new $ZodCheck({ + check: "custom" + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; + } + function custom(fn, _params) { + return _custom(ZodCustom, fn ?? (() => true), _params); + } + function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); + } + function superRefine(fn) { + const ch = check((payload) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, ch._zod.def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); + payload.issues.push(util_exports.issue(_issue)); + } + }; + return fn(payload.value, payload); + }); + return ch; + } + function _instanceof(cls, params = { + error: `Input not instance of ${cls.name}` + }) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util_exports.normalizeParams(params) + }); + inst._zod.bag.Class = cls; + return inst; + } + function json(params) { + const jsonSchema = lazy(() => { + return union([string2(params), number2(), boolean2(), _null3(), array(jsonSchema), record(string2(), jsonSchema)]); + }); + return jsonSchema; + } + function preprocess(fn, schema) { + return pipe(transform(fn), schema); + } + var ZodType, _ZodString, ZodString, ZodStringFormat, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodCustomStringFormat, ZodNumber, ZodNumberFormat, ZodBoolean, ZodBigInt, ZodBigIntFormat, ZodSymbol, ZodUndefined, ZodNull, ZodAny, ZodUnknown, ZodNever, ZodVoid, ZodDate, ZodArray, ZodObject, ZodUnion, ZodDiscriminatedUnion, ZodIntersection, ZodTuple, ZodRecord, ZodMap, ZodSet, ZodEnum, ZodLiteral, ZodFile, ZodTransform, ZodOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodSuccess, ZodCatch, ZodNaN, ZodPipe, ZodReadonly, ZodTemplateLiteral, ZodLazy, ZodPromise, ZodCustom, stringbool; + var init_schemas2 = __esm({ + "node_modules/zod/v4/classic/schemas.js"() { + init_core2(); + init_core2(); + init_checks2(); + init_iso(); + init_parse2(); + ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => { + $ZodType.init(inst, def); + inst.def = def; + Object.defineProperty(inst, "_def", { value: def }); + inst.check = (...checks) => { + return inst.clone( + { + ...def, + checks: [ + ...def.checks ?? [], + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch) + ] + } + // { parent: true } + ); + }; + inst.clone = (def2, params) => clone(inst, def2, params); + inst.brand = () => inst; + inst.register = (reg, meta) => { + reg.add(inst, meta); + return inst; + }; + inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => safeParse3(inst, data, params); + inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params); + inst.spa = inst.safeParseAsync; + inst.refine = (check2, params) => inst.check(refine(check2, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(_overwrite(fn)); + inst.optional = () => optional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg) => union([inst, arg]); + inst.and = (arg) => intersection(inst, arg); + inst.transform = (tx) => pipe(inst, transform(tx)); + inst.default = (def2) => _default2(inst, def2); + inst.prefault = (def2) => prefault(inst, def2); + inst.catch = (params) => _catch2(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + inst.describe = (description) => { + const cl = inst.clone(); + globalRegistry.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true + }); + inst.meta = (...args) => { + if (args.length === 0) { + return globalRegistry.get(inst); + } + const cl = inst.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }; + inst.isOptional = () => inst.safeParse(void 0).success; + inst.isNullable = () => inst.safeParse(null).success; + return inst; + }); + _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + inst.regex = (...args) => inst.check(_regex(...args)); + inst.includes = (...args) => inst.check(_includes(...args)); + inst.startsWith = (...args) => inst.check(_startsWith(...args)); + inst.endsWith = (...args) => inst.check(_endsWith(...args)); + inst.min = (...args) => inst.check(_minLength(...args)); + inst.max = (...args) => inst.check(_maxLength(...args)); + inst.length = (...args) => inst.check(_length(...args)); + inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); + inst.lowercase = (params) => inst.check(_lowercase(params)); + inst.uppercase = (params) => inst.check(_uppercase(params)); + inst.trim = () => inst.check(_trim()); + inst.normalize = (...args) => inst.check(_normalize(...args)); + inst.toLowerCase = () => inst.check(_toLowerCase()); + inst.toUpperCase = () => inst.check(_toUpperCase()); + }); + ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params) => inst.check(_email(ZodEmail, params)); + inst.url = (params) => inst.check(_url(ZodURL, params)); + inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(_xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(_e164(ZodE164, params)); + inst.datetime = (params) => inst.check(datetime2(params)); + inst.date = (params) => inst.check(date2(params)); + inst.time = (params) => inst.check(time2(params)); + inst.duration = (params) => inst.check(duration2(params)); + }); + ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); + }); + ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => { + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => { + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => { + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => { + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => { + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => { + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => { + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => { + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => { + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => { + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => { + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => { + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => { + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => { + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => { + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => { + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => { + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => { + $ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); + }); + ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.int = (params) => inst.check(int(params)); + inst.safe = (params) => inst.check(int(params)); + inst.positive = (params) => inst.check(_gt(0, params)); + inst.nonnegative = (params) => inst.check(_gte(0, params)); + inst.negative = (params) => inst.check(_lt(0, params)); + inst.nonpositive = (params) => inst.check(_lte(0, params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + inst.step = (value, params) => inst.check(_multipleOf(value, params)); + inst.finite = () => inst; + const bag = inst._zod.bag; + inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; + }); + ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); + }); + ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + }); + ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => { + $ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.positive = (params) => inst.check(_gt(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; + }); + ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => { + $ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); + }); + ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => { + $ZodSymbol.init(inst, def); + ZodType.init(inst, def); + }); + ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => { + $ZodUndefined.init(inst, def); + ZodType.init(inst, def); + }); + ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + }); + ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + }); + ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + }); + ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + }); + ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => { + $ZodVoid.init(inst, def); + ZodType.init(inst, def); + }); + ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => { + $ZodDate.init(inst, def); + ZodType.init(inst, def); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; + }); + ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst.element = def.element; + inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); + inst.nonempty = (params) => inst.check(_minLength(1, params)); + inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(_length(len, params)); + inst.unwrap = () => inst.element; + }); + ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => { + $ZodObject.init(inst, def); + ZodType.init(inst, def); + util_exports.defineLazy(inst, "shape", () => def.shape); + inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 }); + inst.extend = (incoming) => { + return util_exports.extend(inst, incoming); + }; + inst.merge = (other) => util_exports.merge(inst, other); + inst.pick = (mask) => util_exports.pick(inst, mask); + inst.omit = (mask) => util_exports.omit(inst, mask); + inst.partial = (...args) => util_exports.partial(ZodOptional, inst, args[0]); + inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]); + }); + ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst.options = def.options; + }); + ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); + }); + ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + }); + ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => { + $ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest + }); + }); + ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + }); + ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => { + $ZodMap.init(inst, def); + ZodType.init(inst, def); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + }); + ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => { + $ZodSet.init(inst, def); + ZodType.init(inst, def); + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); + }); + ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...util_exports.normalizeParams(params), + entries: newEntries + }); + }; + }); + ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + } + }); + }); + ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => { + $ZodFile.init(inst, def); + ZodType.init(inst, def); + inst.min = (size, params) => inst.check(_minSize(size, params)); + inst.max = (size, params) => inst.check(_maxSize(size, params)); + inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); + }); + ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.addIssue = (issue2) => { + if (typeof issue2 === "string") { + payload.issues.push(util_exports.issue(issue2, payload.value, def)); + } else { + const _issue = issue2; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + _issue.continue ?? (_issue.continue = true); + payload.issues.push(util_exports.issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output2) => { + payload.value = output2; + return payload; + }); + } + payload.value = output; + return payload; + }; + }); + ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; + }); + ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => { + $ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; + }); + ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => { + $ZodNaN.init(inst, def); + ZodType.init(inst, def); + }); + ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst.in = def.in; + inst.out = def.out; + }); + ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + }); + ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => { + $ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + }); + ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.getter(); + }); + ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => { + $ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst.unwrap = () => inst._zod.def.innerType; + }); + ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + }); + stringbool = (...args) => _stringbool({ + Pipe: ZodPipe, + Boolean: ZodBoolean, + String: ZodString, + Transform: ZodTransform + }, ...args); + } + }); + + // node_modules/zod/v4/classic/compat.js + function setErrorMap(map2) { + config({ + customError: map2 + }); + } + function getErrorMap() { + return config().customError; + } + var ZodIssueCode; + var init_compat = __esm({ + "node_modules/zod/v4/classic/compat.js"() { + init_core2(); + ZodIssueCode = { + 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" + }; + } + }); + + // node_modules/zod/v4/classic/coerce.js + var coerce_exports = {}; + __export(coerce_exports, { + bigint: () => bigint3, + boolean: () => boolean3, + date: () => date4, + number: () => number3, + string: () => string3 + }); + function string3(params) { + return _coercedString(ZodString, params); + } + function number3(params) { + return _coercedNumber(ZodNumber, params); + } + function boolean3(params) { + return _coercedBoolean(ZodBoolean, params); + } + function bigint3(params) { + return _coercedBigint(ZodBigInt, params); + } + function date4(params) { + return _coercedDate(ZodDate, params); + } + var init_coerce = __esm({ + "node_modules/zod/v4/classic/coerce.js"() { + init_core2(); + init_schemas2(); + } + }); + + // node_modules/zod/v4/classic/external.js + var external_exports = {}; + __export(external_exports, { + $brand: () => $brand, + $input: () => $input, + $output: () => $output, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFile: () => ZodFile, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRealError: () => ZodRealError, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + _ZodString: () => _ZodString, + _default: () => _default2, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + clone: () => clone, + coerce: () => coerce_exports, + config: () => config, + core: () => core_exports2, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + endsWith: () => _endsWith, + enum: () => _enum2, + file: () => file, + flattenError: () => flattenError, + float32: () => float32, + float64: () => float64, + formatError: () => formatError, + function: () => _function, + getErrorMap: () => getErrorMap, + globalRegistry: () => globalRegistry, + gt: () => _gt, + gte: () => _gte, + guid: () => guid2, + includes: () => _includes, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + ipv4: () => ipv42, + ipv6: () => ipv62, + iso: () => iso_exports, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + length: () => _length, + literal: () => literal, + locales: () => locales_exports, + looseObject: () => looseObject, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + map: () => map, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + negative: () => _negative, + never: () => never, + nonnegative: () => _nonnegative, + nonoptional: () => nonoptional, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object2, + optional: () => optional, + overwrite: () => _overwrite, + parse: () => parse2, + parseAsync: () => parseAsync2, + partialRecord: () => partialRecord, + pipe: () => pipe, + positive: () => _positive, + prefault: () => prefault, + preprocess: () => preprocess, + prettifyError: () => prettifyError, + promise: () => promise, + property: () => _property, + readonly: () => readonly, + record: () => record, + refine: () => refine, + regex: () => _regex, + regexes: () => regexes_exports, + registry: () => registry, + safeParse: () => safeParse3, + safeParseAsync: () => safeParseAsync2, + set: () => set, + setErrorMap: () => setErrorMap, + size: () => _size, + startsWith: () => _startsWith, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + toJSONSchema: () => toJSONSchema, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + transform: () => transform, + treeifyError: () => treeifyError, + trim: () => _trim, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + uppercase: () => _uppercase, + url: () => url, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2 + }); + var init_external = __esm({ + "node_modules/zod/v4/classic/external.js"() { + init_core2(); + init_schemas2(); + init_checks2(); + init_errors2(); + init_parse2(); + init_compat(); + init_core2(); + init_en(); + init_core2(); + init_locales(); + init_iso(); + init_iso(); + init_coerce(); + config(en_default()); + } + }); + + // node_modules/zod/v4/classic/index.js + var classic_default; + var init_classic = __esm({ + "node_modules/zod/v4/classic/index.js"() { + init_external(); + init_external(); + classic_default = external_exports; + } + }); + + // node_modules/zod/v4/index.js + var v4_exports = {}; + __export(v4_exports, { + $brand: () => $brand, + $input: () => $input, + $output: () => $output, + NEVER: () => NEVER, + TimePrecision: () => TimePrecision, + ZodAny: () => ZodAny, + ZodArray: () => ZodArray, + ZodBase64: () => ZodBase64, + ZodBase64URL: () => ZodBase64URL, + ZodBigInt: () => ZodBigInt, + ZodBigIntFormat: () => ZodBigIntFormat, + ZodBoolean: () => ZodBoolean, + ZodCIDRv4: () => ZodCIDRv4, + ZodCIDRv6: () => ZodCIDRv6, + ZodCUID: () => ZodCUID, + ZodCUID2: () => ZodCUID2, + ZodCatch: () => ZodCatch, + ZodCustom: () => ZodCustom, + ZodCustomStringFormat: () => ZodCustomStringFormat, + ZodDate: () => ZodDate, + ZodDefault: () => ZodDefault, + ZodDiscriminatedUnion: () => ZodDiscriminatedUnion, + ZodE164: () => ZodE164, + ZodEmail: () => ZodEmail, + ZodEmoji: () => ZodEmoji, + ZodEnum: () => ZodEnum, + ZodError: () => ZodError, + ZodFile: () => ZodFile, + ZodGUID: () => ZodGUID, + ZodIPv4: () => ZodIPv4, + ZodIPv6: () => ZodIPv6, + ZodISODate: () => ZodISODate, + ZodISODateTime: () => ZodISODateTime, + ZodISODuration: () => ZodISODuration, + ZodISOTime: () => ZodISOTime, + ZodIntersection: () => ZodIntersection, + ZodIssueCode: () => ZodIssueCode, + ZodJWT: () => ZodJWT, + ZodKSUID: () => ZodKSUID, + ZodLazy: () => ZodLazy, + ZodLiteral: () => ZodLiteral, + ZodMap: () => ZodMap, + ZodNaN: () => ZodNaN, + ZodNanoID: () => ZodNanoID, + ZodNever: () => ZodNever, + ZodNonOptional: () => ZodNonOptional, + ZodNull: () => ZodNull, + ZodNullable: () => ZodNullable, + ZodNumber: () => ZodNumber, + ZodNumberFormat: () => ZodNumberFormat, + ZodObject: () => ZodObject, + ZodOptional: () => ZodOptional, + ZodPipe: () => ZodPipe, + ZodPrefault: () => ZodPrefault, + ZodPromise: () => ZodPromise, + ZodReadonly: () => ZodReadonly, + ZodRealError: () => ZodRealError, + ZodRecord: () => ZodRecord, + ZodSet: () => ZodSet, + ZodString: () => ZodString, + ZodStringFormat: () => ZodStringFormat, + ZodSuccess: () => ZodSuccess, + ZodSymbol: () => ZodSymbol, + ZodTemplateLiteral: () => ZodTemplateLiteral, + ZodTransform: () => ZodTransform, + ZodTuple: () => ZodTuple, + ZodType: () => ZodType, + ZodULID: () => ZodULID, + ZodURL: () => ZodURL, + ZodUUID: () => ZodUUID, + ZodUndefined: () => ZodUndefined, + ZodUnion: () => ZodUnion, + ZodUnknown: () => ZodUnknown, + ZodVoid: () => ZodVoid, + ZodXID: () => ZodXID, + _ZodString: () => _ZodString, + _default: () => _default2, + any: () => any, + array: () => array, + base64: () => base642, + base64url: () => base64url2, + bigint: () => bigint2, + boolean: () => boolean2, + catch: () => _catch2, + check: () => check, + cidrv4: () => cidrv42, + cidrv6: () => cidrv62, + clone: () => clone, + coerce: () => coerce_exports, + config: () => config, + core: () => core_exports2, + cuid: () => cuid3, + cuid2: () => cuid22, + custom: () => custom, + date: () => date3, + default: () => v4_default, + discriminatedUnion: () => discriminatedUnion, + e164: () => e1642, + email: () => email2, + emoji: () => emoji2, + endsWith: () => _endsWith, + enum: () => _enum2, + file: () => file, + flattenError: () => flattenError, + float32: () => float32, + float64: () => float64, + formatError: () => formatError, + function: () => _function, + getErrorMap: () => getErrorMap, + globalRegistry: () => globalRegistry, + gt: () => _gt, + gte: () => _gte, + guid: () => guid2, + includes: () => _includes, + instanceof: () => _instanceof, + int: () => int, + int32: () => int32, + int64: () => int64, + intersection: () => intersection, + ipv4: () => ipv42, + ipv6: () => ipv62, + iso: () => iso_exports, + json: () => json, + jwt: () => jwt, + keyof: () => keyof, + ksuid: () => ksuid2, + lazy: () => lazy, + length: () => _length, + literal: () => literal, + locales: () => locales_exports, + looseObject: () => looseObject, + lowercase: () => _lowercase, + lt: () => _lt, + lte: () => _lte, + map: () => map, + maxLength: () => _maxLength, + maxSize: () => _maxSize, + mime: () => _mime, + minLength: () => _minLength, + minSize: () => _minSize, + multipleOf: () => _multipleOf, + nan: () => nan, + nanoid: () => nanoid2, + nativeEnum: () => nativeEnum, + negative: () => _negative, + never: () => never, + nonnegative: () => _nonnegative, + nonoptional: () => nonoptional, + nonpositive: () => _nonpositive, + normalize: () => _normalize, + null: () => _null3, + nullable: () => nullable, + nullish: () => nullish2, + number: () => number2, + object: () => object2, + optional: () => optional, + overwrite: () => _overwrite, + parse: () => parse2, + parseAsync: () => parseAsync2, + partialRecord: () => partialRecord, + pipe: () => pipe, + positive: () => _positive, + prefault: () => prefault, + preprocess: () => preprocess, + prettifyError: () => prettifyError, + promise: () => promise, + property: () => _property, + readonly: () => readonly, + record: () => record, + refine: () => refine, + regex: () => _regex, + regexes: () => regexes_exports, + registry: () => registry, + safeParse: () => safeParse3, + safeParseAsync: () => safeParseAsync2, + set: () => set, + setErrorMap: () => setErrorMap, + size: () => _size, + startsWith: () => _startsWith, + strictObject: () => strictObject, + string: () => string2, + stringFormat: () => stringFormat, + stringbool: () => stringbool, + success: () => success, + superRefine: () => superRefine, + symbol: () => symbol, + templateLiteral: () => templateLiteral, + toJSONSchema: () => toJSONSchema, + toLowerCase: () => _toLowerCase, + toUpperCase: () => _toUpperCase, + transform: () => transform, + treeifyError: () => treeifyError, + trim: () => _trim, + tuple: () => tuple, + uint32: () => uint32, + uint64: () => uint64, + ulid: () => ulid2, + undefined: () => _undefined3, + union: () => union, + unknown: () => unknown, + uppercase: () => _uppercase, + url: () => url, + uuid: () => uuid2, + uuidv4: () => uuidv4, + uuidv6: () => uuidv6, + uuidv7: () => uuidv7, + void: () => _void2, + xid: () => xid2, + z: () => external_exports + }); + var v4_default; + var init_v4 = __esm({ + "node_modules/zod/v4/index.js"() { + init_classic(); + init_classic(); + v4_default = classic_default; + } + }); + + // node_modules/zod/v4/mini/parse.js + init_core2(); + + // node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js + function isZ4Schema(s) { + const schema = s; + return !!schema._zod; + } + function safeParse2(schema, data) { + if (isZ4Schema(schema)) { + const result2 = safeParse(schema, data); + return result2; + } + const v3Schema = schema; + const result = v3Schema.safeParse(data); + return result; + } + function getObjectShape(schema) { + if (!schema) + return void 0; + let rawShape; + if (isZ4Schema(schema)) { + const v4Schema = schema; + rawShape = v4Schema._zod?.def?.shape; + } else { + const v3Schema = schema; + rawShape = v3Schema.shape; + } + if (!rawShape) + return void 0; + if (typeof rawShape === "function") { + try { + return rawShape(); + } catch { + return void 0; + } + } + return rawShape; + } + function getLiteralValue(schema) { + if (isZ4Schema(schema)) { + const v4Schema = schema; + const def2 = v4Schema._zod?.def; + if (def2) { + if (def2.value !== void 0) + return def2.value; + if (Array.isArray(def2.values) && def2.values.length > 0) { + return def2.values[0]; + } + } + } + const v3Schema = schema; + const def = v3Schema._def; + if (def) { + if (def.value !== void 0) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + const directValue = schema.value; + if (directValue !== void 0) + return directValue; + return void 0; + } + + // node_modules/@modelcontextprotocol/sdk/dist/esm/types.js + init_v4(); + var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; + var JSONRPC_VERSION = "2.0"; + var AssertObjectSchema = custom((v2) => v2 !== null && (typeof v2 === "object" || typeof v2 === "function")); + var ProgressTokenSchema = union([string2(), number2().int()]); + var CursorSchema = string2(); + var TaskCreationParamsSchema = looseObject({ + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl: number2().optional(), + /** + * Time in milliseconds to wait between task status requests. + */ + pollInterval: number2().optional() + }); + var TaskMetadataSchema = object2({ + ttl: number2().optional() + }); + var RelatedTaskMetadataSchema = object2({ + taskId: string2() + }); + var RequestMetaSchema = looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional(), + /** + * If specified, this request is related to the provided task. + */ + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() + }); + var BaseRequestParamsSchema = object2({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() + }); + var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * If specified, the caller is requesting task-augmented execution for this request. + * The request will return a CreateTaskResult immediately, and the actual result can be + * retrieved later via tasks/result. + * + * Task augmentation is subject to capability negotiation - receivers MUST declare support + * for task augmentation of specific request types in their capabilities. + */ + task: TaskMetadataSchema.optional() + }); + var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; + var RequestSchema = object2({ + method: string2(), + params: BaseRequestParamsSchema.loose().optional() + }); + var NotificationsParamsSchema = object2({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() + }); + var NotificationSchema = object2({ + method: string2(), + params: NotificationsParamsSchema.loose().optional() + }); + var ResultSchema = looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: RequestMetaSchema.optional() + }); + var RequestIdSchema = union([string2(), number2().int()]); + var JSONRPCRequestSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape + }).strict(); + var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; + var JSONRPCNotificationSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape + }).strict(); + var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; + var JSONRPCResultResponseSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema + }).strict(); + var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; + var ErrorCode; + (function(ErrorCode2) { + ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed"; + ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout"; + ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError"; + ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError"; + ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + })(ErrorCode || (ErrorCode = {})); + var JSONRPCErrorResponseSchema = object2({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: object2({ + /** + * The error type that occurred. + */ + code: number2().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string2(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: unknown().optional() + }) + }).strict(); + var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; + var JSONRPCMessageSchema = union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema + ]); + var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); + var EmptyResultSchema = ResultSchema.strict(); + var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema.optional(), + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: string2().optional() + }); + var CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema + }); + var IconSchema = object2({ + /** + * URL or data URI for the icon. + */ + src: string2(), + /** + * Optional MIME type for the icon. + */ + mimeType: string2().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: array(string2()).optional(), + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme: _enum2(["light", "dark"]).optional() + }); + var IconsSchema = object2({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons: array(IconSchema).optional() + }); + var BaseMetadataSchema = object2({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: string2(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: string2().optional() + }); + var ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: string2(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: string2().optional(), + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description: string2().optional() + }); + var FormElicitationCapabilitySchema = intersection(object2({ + applyDefaults: boolean2().optional() + }), record(string2(), unknown())); + var ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value)) { + if (Object.keys(value).length === 0) { + return { form: {} }; + } + } + return value; + }, intersection(object2({ + form: FormElicitationCapabilitySchema.optional(), + url: AssertObjectSchema.optional() + }), record(string2(), unknown()).optional())); + var ClientTasksCapabilitySchema = looseObject({ + /** + * Present if the client supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the client supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for sampling requests. + */ + sampling: looseObject({ + createMessage: AssertObjectSchema.optional() + }).optional(), + /** + * Task support for elicitation requests. + */ + elicitation: looseObject({ + create: AssertObjectSchema.optional() + }).optional() + }).optional() + }); + var ServerTasksCapabilitySchema = looseObject({ + /** + * Present if the server supports listing tasks. + */ + list: AssertObjectSchema.optional(), + /** + * Present if the server supports cancelling tasks. + */ + cancel: AssertObjectSchema.optional(), + /** + * Capabilities for task creation on specific request types. + */ + requests: looseObject({ + /** + * Task support for tool requests. + */ + tools: looseObject({ + call: AssertObjectSchema.optional() + }).optional() + }).optional() + }); + var ClientCapabilitiesSchema = object2({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: record(string2(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: object2({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }).optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: object2({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the client supports task creation. + */ + tasks: ClientTasksCapabilitySchema.optional(), + /** + * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: record(string2(), AssertObjectSchema).optional() + }); + var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string2(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema + }); + var InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema + }); + var ServerCapabilitiesSchema = object2({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: record(string2(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: object2({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server offers any resources to read. + */ + resources: object2({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: boolean2().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server offers any tools to call. + */ + tools: object2({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: boolean2().optional() + }).optional(), + /** + * Present if the server supports task creation. + */ + tasks: ServerTasksCapabilitySchema.optional(), + /** + * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name). + */ + extensions: record(string2(), AssertObjectSchema).optional() + }); + var InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string2(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: string2().optional() + }); + var InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() + }); + var PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() + }); + var ProgressSchema = object2({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: number2(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: optional(number2()), + /** + * An optional message describing the current progress. + */ + message: optional(string2()) + }); + var ProgressNotificationParamsSchema = object2({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema + }); + var ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema + }); + var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: CursorSchema.optional() + }); + var PaginatedRequestSchema = RequestSchema.extend({ + params: PaginatedRequestParamsSchema.optional() + }); + var PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: CursorSchema.optional() + }); + var TaskStatusSchema = _enum2(["working", "input_required", "completed", "failed", "cancelled"]); + var TaskSchema = object2({ + taskId: string2(), + status: TaskStatusSchema, + /** + * Time in milliseconds to keep task results available after completion. + * If null, the task has unlimited lifetime until manually cleaned up. + */ + ttl: union([number2(), _null3()]), + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string2(), + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string2(), + pollInterval: optional(number2()), + /** + * Optional diagnostic message for failed tasks or other status information. + */ + statusMessage: optional(string2()) + }); + var CreateTaskResultSchema = ResultSchema.extend({ + task: TaskSchema + }); + var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); + var TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema + }); + var GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) + }); + var GetTaskResultSchema = ResultSchema.merge(TaskSchema); + var GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) + }); + var GetTaskPayloadResultSchema = ResultSchema.loose(); + var ListTasksRequestSchema = PaginatedRequestSchema.extend({ + method: literal("tasks/list") + }); + var ListTasksResultSchema = PaginatedResultSchema.extend({ + tasks: array(TaskSchema) + }); + var CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ + taskId: string2() + }) + }); + var CancelTaskResultSchema = ResultSchema.merge(TaskSchema); + var ResourceContentsSchema = object2({ + /** + * The URI of this resource. + */ + uri: string2(), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string2()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var TextResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string2() + }); + var Base64Schema = string2().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + var BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema + }); + var RoleSchema = _enum2(["user", "assistant"]); + var AnnotationsSchema = object2({ + /** + * Intended audience(s) for the resource. + */ + audience: array(RoleSchema).optional(), + /** + * Importance hint for the resource, from 0 (least) to 1 (most). + */ + priority: number2().min(0).max(1).optional(), + /** + * ISO 8601 timestamp for the most recent modification. + */ + lastModified: iso_exports.datetime({ offset: true }).optional() + }); + var ResourceSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: string2(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string2()), + /** + * The MIME type of this resource, if known. + */ + mimeType: optional(string2()), + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size: optional(number2()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) + }); + var ResourceTemplateSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: string2(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: optional(string2()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: optional(string2()), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) + }); + var ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: literal("resources/list") + }); + var ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: array(ResourceSchema) + }); + var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ + method: literal("resources/templates/list") + }); + var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: array(ResourceTemplateSchema) + }); + var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string2() + }); + var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; + var ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema + }); + var ReadResourceResultSchema = ResultSchema.extend({ + contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema])) + }); + var ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() + }); + var SubscribeRequestParamsSchema = ResourceRequestParamsSchema; + var SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema + }); + var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; + var UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema + }); + var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: string2() + }); + var ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema + }); + var PromptArgumentSchema = object2({ + /** + * The name of the argument. + */ + name: string2(), + /** + * A human-readable description of the argument. + */ + description: optional(string2()), + /** + * Whether this argument must be provided. + */ + required: optional(boolean2()) + }); + var PromptSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: optional(string2()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: optional(array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: optional(looseObject({})) + }); + var ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: literal("prompts/list") + }); + var ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: array(PromptSchema) + }); + var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: string2(), + /** + * Arguments to use for templating the prompt. + */ + arguments: record(string2(), string2()).optional() + }); + var GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema + }); + var TextContentSchema = object2({ + type: literal("text"), + /** + * The text content of the message. + */ + text: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var ImageContentSchema = object2({ + type: literal("image"), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var AudioContentSchema = object2({ + type: literal("audio"), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string2(), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var ToolUseContentSchema = object2({ + type: literal("tool_use"), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: string2(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: string2(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: record(string2(), unknown()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var EmbeddedResourceSchema = object2({ + type: literal("resource"), + resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * Optional annotations for the client. + */ + annotations: AnnotationsSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var ResourceLinkSchema = ResourceSchema.extend({ + type: literal("resource_link") + }); + var ContentBlockSchema = union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema + ]); + var PromptMessageSchema = object2({ + role: RoleSchema, + content: ContentBlockSchema + }); + var GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: string2().optional(), + messages: array(PromptMessageSchema) + }); + var PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() + }); + var ToolAnnotationsSchema = object2({ + /** + * A human-readable title for the tool. + */ + title: string2().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: boolean2().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: boolean2().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: boolean2().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: boolean2().optional() + }); + var ToolExecutionSchema = object2({ + /** + * Indicates the tool's preference for task-augmented execution. + * - "required": Clients MUST invoke the tool as a task + * - "optional": Clients MAY invoke the tool as a task or normal request + * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task + * + * If not present, defaults to "forbidden". + */ + taskSupport: _enum2(["required", "optional", "forbidden"]).optional() + }); + var ToolSchema = object2({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: string2().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: object2({ + type: literal("object"), + properties: record(string2(), AssertObjectSchema).optional(), + required: array(string2()).optional() + }).catchall(unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: object2({ + type: literal("object"), + properties: record(string2(), AssertObjectSchema).optional(), + required: array(string2()).optional() + }).catchall(unknown()).optional(), + /** + * Optional additional tool information. + */ + annotations: ToolAnnotationsSchema.optional(), + /** + * Execution-related properties for this tool. + */ + execution: ToolExecutionSchema.optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: literal("tools/list") + }); + var ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: array(ToolSchema) + }); + var CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: array(ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: record(string2(), unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: boolean2().optional() + }); + var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ + toolResult: unknown() + })); + var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: string2(), + /** + * Arguments to pass to the tool. + */ + arguments: record(string2(), unknown()).optional() + }); + var CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema + }); + var ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() + }); + var ListChangedOptionsBaseSchema = object2({ + /** + * If true, the list will be refreshed automatically when a list changed notification is received. + * The callback will be called with the updated list. + * + * If false, the callback will be called with null items, allowing manual refresh. + * + * @default true + */ + autoRefresh: boolean2().default(true), + /** + * Debounce time in milliseconds for list changed notification processing. + * + * Multiple notifications received within this timeframe will only trigger one refresh. + * Set to 0 to disable debouncing. + * + * @default 300 + */ + debounceMs: number2().int().nonnegative().default(300) + }); + var LoggingLevelSchema = _enum2(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]); + var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: LoggingLevelSchema + }); + var SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema + }); + var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: string2().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown() + }); + var LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema + }); + var ModelHintSchema = object2({ + /** + * A hint for a model name. + */ + name: string2().optional() + }); + var ModelPreferencesSchema = object2({ + /** + * Optional hints to use for model selection. + */ + hints: array(ModelHintSchema).optional(), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: number2().min(0).max(1).optional(), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: number2().min(0).max(1).optional(), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: number2().min(0).max(1).optional() + }); + var ToolChoiceSchema = object2({ + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: _enum2(["auto", "required", "none"]).optional() + }); + var ToolResultContentSchema = object2({ + type: literal("tool_result"), + toolUseId: string2().describe("The unique identifier for the corresponding tool call."), + content: array(ContentBlockSchema).default([]), + structuredContent: object2({}).loose().optional(), + isError: boolean2().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]); + var SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema + ]); + var SamplingMessageSchema = object2({ + role: RoleSchema, + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + messages: array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: string2().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: _enum2(["none", "thisServer", "allServers"]).optional(), + temperature: number2().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number2().int(), + stopSequences: array(string2()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: array(ToolSchema).optional(), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: ToolChoiceSchema.optional() + }); + var CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema + }); + var CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: string2(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens"]).or(string2())), + role: RoleSchema, + /** + * Response content. Single content block (text, image, or audio). + */ + content: SamplingContentSchema + }); + var CreateMessageResultWithToolsSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: string2(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())), + role: RoleSchema, + /** + * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". + */ + content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]) + }); + var BooleanSchemaSchema = object2({ + type: literal("boolean"), + title: string2().optional(), + description: string2().optional(), + default: boolean2().optional() + }); + var StringSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + minLength: number2().optional(), + maxLength: number2().optional(), + format: _enum2(["email", "uri", "date", "date-time"]).optional(), + default: string2().optional() + }); + var NumberSchemaSchema = object2({ + type: _enum2(["number", "integer"]), + title: string2().optional(), + description: string2().optional(), + minimum: number2().optional(), + maximum: number2().optional(), + default: number2().optional() + }); + var UntitledSingleSelectEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + default: string2().optional() + }); + var TitledSingleSelectEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + oneOf: array(object2({ + const: string2(), + title: string2() + })), + default: string2().optional() + }); + var LegacyTitledEnumSchemaSchema = object2({ + type: literal("string"), + title: string2().optional(), + description: string2().optional(), + enum: array(string2()), + enumNames: array(string2()).optional(), + default: string2().optional() + }); + var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); + var UntitledMultiSelectEnumSchemaSchema = object2({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object2({ + type: literal("string"), + enum: array(string2()) + }), + default: array(string2()).optional() + }); + var TitledMultiSelectEnumSchemaSchema = object2({ + type: literal("array"), + title: string2().optional(), + description: string2().optional(), + minItems: number2().optional(), + maxItems: number2().optional(), + items: object2({ + anyOf: array(object2({ + const: string2(), + title: string2() + })) + }), + default: array(string2()).optional() + }); + var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); + var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); + var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); + var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + * + * Optional for backward compatibility. Clients MUST treat missing mode as "form". + */ + mode: literal("form").optional(), + /** + * The message to present to the user describing what information is being requested. + */ + message: string2(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: object2({ + type: literal("object"), + properties: record(string2(), PrimitiveSchemaDefinitionSchema), + required: array(string2()).optional() + }) + }); + var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: literal("url"), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string2(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string2(), + /** + * The URL that the user should navigate to. + */ + url: string2().url() + }); + var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); + var ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema + }); + var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: string2() + }); + var ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema + }); + var ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: _enum2(["accept", "decline", "cancel"]), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + * Per MCP spec, content is "typically omitted" for decline/cancel actions. + * We normalize null to undefined for leniency while maintaining type compatibility. + */ + content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()) + }); + var ResourceTemplateReferenceSchema = object2({ + type: literal("ref/resource"), + /** + * The URI or URI template of the resource. + */ + uri: string2() + }); + var PromptReferenceSchema = object2({ + type: literal("ref/prompt"), + /** + * The name of the prompt or prompt template + */ + name: string2() + }); + var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: object2({ + /** + * The name of the argument + */ + name: string2(), + /** + * The value of the argument to use for completion matching. + */ + value: string2() + }), + context: object2({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: record(string2(), string2()).optional() + }).optional() + }); + var CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema + }); + var CompleteResultSchema = ResultSchema.extend({ + completion: looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: array(string2()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: optional(number2().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: optional(boolean2()) + }) + }); + var RootSchema = object2({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: string2().startsWith("file://"), + /** + * An optional name for the root. + */ + name: string2().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: record(string2(), unknown()).optional() + }); + var ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() + }); + var ListRootsResultSchema = ResultSchema.extend({ + roots: array(RootSchema) + }); + var RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() + }); + var ClientRequestSchema = union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema + ]); + var ClientNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, + TaskStatusNotificationSchema + ]); + var ClientResultSchema = union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema + ]); + var ServerRequestSchema = union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + GetTaskRequestSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + CancelTaskRequestSchema + ]); + var ServerNotificationSchema = union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + TaskStatusNotificationSchema, + ElicitationCompleteNotificationSchema + ]); + var ServerResultSchema = union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, + GetTaskResultSchema, + ListTasksResultSchema, + CreateTaskResultSchema + ]); + var McpError = class _McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = "McpError"; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } + } + return new _McpError(code, message, data); + } + }; + var UrlElicitationRequiredError = class extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations + }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } + }; + + // node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js + function isTerminal(status) { + return status === "completed" || status === "failed" || status === "cancelled"; + } + + // node_modules/zod-to-json-schema/dist/esm/Options.js + var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); + + // node_modules/zod-to-json-schema/dist/esm/parsers/string.js + var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); + + // node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js + function getMethodLiteral(schema) { + const shape = getObjectShape(schema); + const methodSchema = shape?.method; + if (!methodSchema) { + throw new Error("Schema is missing a method literal"); + } + const value = getLiteralValue(methodSchema); + if (typeof value !== "string") { + throw new Error("Schema method literal must be a string"); + } + return value; + } + function parseWithCompat(schema, data) { + const result = safeParse2(schema, data); + if (!result.success) { + throw result.error; + } + return result.data; + } + + // node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js + var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; + var Protocol = class { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = /* @__PURE__ */ new Map(); + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + this._notificationHandlers = /* @__PURE__ */ new Map(); + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers = /* @__PURE__ */ new Map(); + this._timeoutInfo = /* @__PURE__ */ new Map(); + this._pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + this._taskProgressTokens = /* @__PURE__ */ new Map(); + this._requestResolvers = /* @__PURE__ */ new Map(); + this.setNotificationHandler(CancelledNotificationSchema, (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler(ProgressNotificationSchema, (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler( + PingRequestSchema, + // Automatic pong by default. + (_request) => ({}) + ); + this._taskStore = _options?.taskStore; + this._taskMessageQueue = _options?.taskMessageQueue; + if (this._taskStore) { + this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + } + return { + ...task + }; + }); + this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { + const handleTaskResult = async () => { + const taskId = request.params.taskId; + if (!await this._taskStore.getTask(taskId, extra.sessionId)) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + if (this._taskMessageQueue) { + let queuedMessage; + while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) { + if (queuedMessage.type === "response" || queuedMessage.type === "error") { + const message = queuedMessage.message; + const requestId = message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + this._requestResolvers.delete(requestId); + if (queuedMessage.type === "response") { + resolver(message); + } else { + const errorMessage = message; + const error40 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); + resolver(error40); + } + } else { + const messageType = queuedMessage.type === "response" ? "Response" : "Error"; + this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); + } + continue; + } + await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); + } + } + const task = await this._taskStore.getTask(taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); + } + if (!isTerminal(task.status)) { + await this._waitForTaskUpdate(taskId, extra.signal, extra.sessionId); + return await handleTaskResult(); + } + if (isTerminal(task.status)) { + const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); + this._clearTaskQueue(taskId, extra.sessionId); + return { + ...result, + _meta: { + ...result._meta, + [RELATED_TASK_META_KEY]: { + taskId + } + } + }; + } + return await handleTaskResult(); + }; + return await handleTaskResult(); + }); + this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { + try { + const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); + return { + tasks, + nextCursor, + _meta: {} + }; + } catch (error40) { + throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error40 instanceof Error ? error40.message : String(error40)}`); + } + }); + this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { + try { + const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); + } + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); + } + await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId); + this._clearTaskQueue(request.params.taskId, extra.sessionId); + const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); + if (!cancelledTask) { + throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); + } + return { + _meta: {}, + ...cancelledTask + }; + } catch (error40) { + if (error40 instanceof McpError) { + throw error40; + } + throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error40 instanceof Error ? error40.message : String(error40)}`); + } + }); + } + } + async _oncancel(notification) { + if (!notification.params.requestId) { + return; + } + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + if (this._transport) { + throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection."); + } + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + _onclose?.(); + this._onclose(); + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error40) => { + _onerror?.(error40); + this._onerror(error40); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._onresponse(message); + } else if (isJSONRPCRequest(message)) { + this._onrequest(message, extra); + } else if (isJSONRPCNotification(message)) { + this._onnotification(message); + } else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); + } + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._taskProgressTokens.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) { + clearTimeout(info.timeoutId); + } + this._timeoutInfo.clear(); + for (const controller of this._requestHandlerAbortControllers.values()) { + controller.abort(); + } + this._requestHandlerAbortControllers.clear(); + const error40 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + this.onclose?.(); + for (const handler of responseHandlers.values()) { + handler(error40); + } + } + _onerror(error40) { + this.onerror?.(error40); + } + _onnotification(notification) { + const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; + if (handler === void 0) { + return; + } + Promise.resolve().then(() => handler(notification)).catch((error40) => this._onerror(new Error(`Uncaught error in notification handler: ${error40}`))); + } + _onrequest(request, extra) { + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + const capturedTransport = this._transport; + const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; + const sessionId = capturedTransport?.sessionId; + const store = this._taskStore; + let relatedTaskFound = true; + let relatedTaskLookup; + if (relatedTaskId && store && this._taskMessageQueue && sessionId !== void 0) { + relatedTaskFound = false; + relatedTaskLookup = (async () => { + if (!await store.getTask(relatedTaskId, sessionId)) { + throw new McpError(ErrorCode.InvalidParams, `Task not found: ${relatedTaskId}`); + } + relatedTaskFound = true; + })(); + } + if (handler === void 0) { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: ErrorCode.MethodNotFound, + message: "Method not found" + } + }; + if (relatedTaskId && relatedTaskLookup) { + const queuedError = { type: "error", message: errorResponse, timestamp: Date.now() }; + relatedTaskLookup.then(() => this._enqueueTaskMessage(relatedTaskId, queuedError, sessionId), () => capturedTransport?.send(errorResponse)).catch((error40) => this._onerror(new Error(`Failed to send an error response: ${error40}`))); + } else if (relatedTaskId && this._taskMessageQueue) { + this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId).catch((error40) => this._onerror(new Error(`Failed to enqueue error response: ${error40}`))); + } else { + capturedTransport?.send(errorResponse).catch((error40) => this._onerror(new Error(`Failed to send an error response: ${error40}`))); + } + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0; + const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : void 0; + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport?.sessionId, + _meta: request.params?._meta, + sendNotification: async (notification) => { + if (abortController.signal.aborted) + return; + const notificationOptions = { relatedRequestId: request.id }; + if (relatedTaskId) { + notificationOptions.relatedTask = { taskId: relatedTaskId }; + } + await this.notification(notification, notificationOptions); + }, + sendRequest: async (r, resultSchema, options) => { + if (abortController.signal.aborted) { + throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); + } + const requestOptions = { ...options, relatedRequestId: request.id }; + if (relatedTaskId && !requestOptions.relatedTask) { + requestOptions.relatedTask = { taskId: relatedTaskId }; + } + const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; + if (effectiveTaskId && taskStore) { + await taskStore.updateTaskStatus(effectiveTaskId, "input_required"); + } + return await this.request(r, resultSchema, requestOptions); + }, + authInfo: extra?.authInfo, + requestId: request.id, + requestInfo: extra?.requestInfo, + taskId: relatedTaskId, + taskStore, + taskRequestedTtl: taskCreationParams?.ttl, + closeSSEStream: extra?.closeSSEStream, + closeStandaloneSSEStream: extra?.closeStandaloneSSEStream + }; + (relatedTaskLookup ?? Promise.resolve()).then(() => { + if (relatedTaskLookup && abortController.signal.aborted) { + throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled"); + } + if (taskCreationParams) { + this.assertTaskHandlerCapability(request.method); + } + }).then(() => handler(request, fullExtra)).then(async (result) => { + if (abortController.signal.aborted) { + return; + } + const response = { + result, + jsonrpc: "2.0", + id: request.id + }; + if (relatedTaskId && this._taskMessageQueue) { + await this._enqueueTaskMessage(relatedTaskId, { + type: "response", + message: response, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } else { + await capturedTransport?.send(response); + } + }, async (error40) => { + if (abortController.signal.aborted) { + return; + } + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: Number.isSafeInteger(error40["code"]) ? error40["code"] : ErrorCode.InternalError, + message: error40.message ?? "Internal error", + ...error40["data"] !== void 0 && { data: error40["data"] } + } + }; + if (relatedTaskId && this._taskMessageQueue && relatedTaskFound) { + await this._enqueueTaskMessage(relatedTaskId, { + type: "error", + message: errorResponse, + timestamp: Date.now() + }, capturedTransport?.sessionId); + } else { + await capturedTransport?.send(errorResponse); + } + }).catch((error40) => this._onerror(new Error(`Failed to send response: ${error40}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) { + this._requestHandlerAbortControllers.delete(request.id); + } + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } catch (error40) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error40); + return; + } + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + const resolver = this._requestResolvers.get(messageId); + if (resolver) { + this._requestResolvers.delete(messageId); + if (isJSONRPCResultResponse(response)) { + resolver(response); + } else { + const error40 = new McpError(response.error.code, response.error.message, response.error.data); + resolver(error40); + } + return; + } + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + let isTaskResponse = false; + if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") { + const result = response.result; + if (result.task && typeof result.task === "object") { + const task = result.task; + if (typeof task.taskId === "string") { + isTaskResponse = true; + this._taskProgressTokens.set(task.taskId, messageId); + } + } + } + if (!isTaskResponse) { + this._progressHandlers.delete(messageId); + } + if (isJSONRPCResultResponse(response)) { + handler(response); + } else { + const error40 = McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error40); + } + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + /** + * Sends a request and returns an AsyncGenerator that yields response messages. + * The generator is guaranteed to end with either a 'result' or 'error' message. + * + * @example + * ```typescript + * const stream = protocol.requestStream(request, resultSchema, options); + * for await (const message of stream) { + * switch (message.type) { + * case 'taskCreated': + * console.log('Task created:', message.task.taskId); + * break; + * case 'taskStatus': + * console.log('Task status:', message.task.status); + * break; + * case 'result': + * console.log('Final result:', message.result); + * break; + * case 'error': + * console.error('Error:', message.error); + * break; + * } + * } + * ``` + * + * @experimental Use `client.experimental.tasks.requestStream()` to access this method. + */ + async *requestStream(request, resultSchema, options) { + const { task } = options ?? {}; + if (!task) { + try { + const result = await this.request(request, resultSchema, options); + yield { type: "result", result }; + } catch (error40) { + yield { + type: "error", + error: error40 instanceof McpError ? error40 : new McpError(ErrorCode.InternalError, String(error40)) + }; + } + return; + } + let taskId; + try { + const createResult = await this.request(request, CreateTaskResultSchema, options); + if (createResult.task) { + taskId = createResult.task.taskId; + yield { type: "taskCreated", task: createResult.task }; + } else { + throw new McpError(ErrorCode.InternalError, "Task creation did not return a task"); + } + while (true) { + const task2 = await this.getTask({ taskId }, options); + yield { type: "taskStatus", task: task2 }; + if (isTerminal(task2.status)) { + if (task2.status === "completed") { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: "result", result }; + } else if (task2.status === "failed") { + yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) + }; + } else if (task2.status === "cancelled") { + yield { + type: "error", + error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) + }; + } + return; + } + if (task2.status === "input_required") { + const result = await this.getTaskResult({ taskId }, resultSchema, options); + yield { type: "result", result }; + return; + } + const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3; + await new Promise((resolve) => setTimeout(resolve, pollInterval)); + options?.signal?.throwIfAborted(); + } + } catch (error40) { + yield { + type: "error", + error: error40 instanceof McpError ? error40 : new McpError(ErrorCode.InternalError, String(error40)) + }; + } + } + /** + * Sends a request and waits for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; + return new Promise((resolve, reject) => { + const earlyReject = (error40) => { + reject(error40); + }; + if (!this._transport) { + earlyReject(new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) { + try { + this.assertCapabilityForMethod(request.method); + if (task) { + this.assertTaskCapability(request.method); + } + } catch (e) { + earlyReject(e); + return; + } + } + options?.signal?.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta || {}, + progressToken: messageId + } + }; + } + if (task) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + task + }; + } + if (relatedTask) { + jsonrpcRequest.params = { + ...jsonrpcRequest.params, + _meta: { + ...jsonrpcRequest.params?._meta || {}, + [RELATED_TASK_META_KEY]: relatedTask + } + }; + } + const cancel = (reason) => { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._transport?.send({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error41) => this._onerror(new Error(`Failed to send cancellation: ${error41}`))); + const error40 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); + reject(error40); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = safeParse2(resultSchema, response.result); + if (!parseResult.success) { + reject(parseResult.error); + } else { + resolve(parseResult.data); + } + } catch (error40) { + reject(error40); + } + }); + options?.signal?.addEventListener("abort", () => { + cancel(options?.signal?.reason); + }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + const relatedTaskId = relatedTask?.taskId; + if (relatedTaskId) { + const responseResolver = (response) => { + const handler = this._responseHandlers.get(messageId); + if (handler) { + handler(response); + } else { + this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); + } + }; + this._requestResolvers.set(messageId, responseResolver); + this._enqueueTaskMessage(relatedTaskId, { + type: "request", + message: jsonrpcRequest, + timestamp: Date.now() + }).catch((error40) => { + this._cleanupTimeout(messageId); + reject(error40); + }); + } else { + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error40) => { + this._cleanupTimeout(messageId); + reject(error40); + }); + } + }); + } + /** + * Gets the current status of a task. + * + * @experimental Use `client.experimental.tasks.getTask()` to access this method. + */ + async getTask(params, options) { + return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options); + } + /** + * Retrieves the result of a completed task. + * + * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. + */ + async getTaskResult(params, resultSchema, options) { + return this.request({ method: "tasks/result", params }, resultSchema, options); + } + /** + * Lists tasks, optionally starting from a pagination cursor. + * + * @experimental Use `client.experimental.tasks.listTasks()` to access this method. + */ + async listTasks(params, options) { + return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options); + } + /** + * Cancels a specific task. + * + * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. + */ + async cancelTask(params, options) { + return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + if (!this._transport) { + throw new Error("Not connected"); + } + this.assertNotificationCapability(notification.method); + const relatedTaskId = options?.relatedTask?.taskId; + if (relatedTaskId) { + const jsonrpcNotification2 = { + ...notification, + jsonrpc: "2.0", + params: { + ...notification.params, + _meta: { + ...notification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + await this._enqueueTaskMessage(relatedTaskId, { + type: "notification", + message: jsonrpcNotification2, + timestamp: Date.now() + }); + return; + } + const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; + if (canDebounce) { + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) { + return; + } + let jsonrpcNotification2 = { + ...notification, + jsonrpc: "2.0" + }; + if (options?.relatedTask) { + jsonrpcNotification2 = { + ...jsonrpcNotification2, + params: { + ...jsonrpcNotification2.params, + _meta: { + ...jsonrpcNotification2.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + this._transport?.send(jsonrpcNotification2, options).catch((error40) => this._onerror(error40)); + }); + return; + } + let jsonrpcNotification = { + ...notification, + jsonrpc: "2.0" + }; + if (options?.relatedTask) { + jsonrpcNotification = { + ...jsonrpcNotification, + params: { + ...jsonrpcNotification.params, + _meta: { + ...jsonrpcNotification.params?._meta || {}, + [RELATED_TASK_META_KEY]: options.relatedTask + } + } + }; + } + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = getMethodLiteral(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = parseWithCompat(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = getMethodLiteral(notificationSchema); + this._notificationHandlers.set(method, (notification) => { + const parsed = parseWithCompat(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } + /** + * Cleans up the progress handler associated with a task. + * This should be called when a task reaches a terminal status. + */ + _cleanupTaskProgressHandler(taskId) { + const progressToken = this._taskProgressTokens.get(taskId); + if (progressToken !== void 0) { + this._progressHandlers.delete(progressToken); + this._taskProgressTokens.delete(taskId); + } + } + /** + * Enqueues a task-related message for side-channel delivery via tasks/result. + * @param taskId The task ID to associate the message with + * @param message The message to enqueue + * @param sessionId Optional session ID for binding the operation to a specific session + * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) + * + * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle + * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer + * simply propagates the error. + */ + async _enqueueTaskMessage(taskId, message, sessionId) { + if (!this._taskStore || !this._taskMessageQueue) { + throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured"); + } + const maxQueueSize = this._options?.maxTaskQueueSize; + await this._taskMessageQueue.enqueue(taskId, message, sessionId ?? this._transport?.sessionId, maxQueueSize); + } + /** + * Clears the message queue for a task and rejects any pending request resolvers. + * @param taskId The task ID whose queue should be cleared + * @param sessionId Optional session ID for binding the operation to a specific session + */ + async _clearTaskQueue(taskId, sessionId) { + if (this._taskMessageQueue) { + const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); + for (const message of messages) { + if (message.type === "request" && isJSONRPCRequest(message.message)) { + const requestId = message.message.id; + const resolver = this._requestResolvers.get(requestId); + if (resolver) { + resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed")); + this._requestResolvers.delete(requestId); + } else { + this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); + } + } + } + } + } + /** + * Waits for a task update (new messages or status change) with abort signal support. + * Uses polling to check for updates at the task's configured poll interval. + * @param taskId The task ID to wait for + * @param signal Abort signal to cancel the wait + * @param sessionId Session of the request that waits, passed to the task store + * @returns Promise that resolves when an update occurs or rejects if aborted + */ + async _waitForTaskUpdate(taskId, signal, sessionId) { + let interval = this._options?.defaultTaskPollInterval ?? 1e3; + try { + const task = await this._taskStore?.getTask(taskId, sessionId); + if (task?.pollInterval) { + interval = task.pollInterval; + } + } catch { + } + return new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + return; + } + const timeoutId = setTimeout(resolve, interval); + signal.addEventListener("abort", () => { + clearTimeout(timeoutId); + reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled")); + }, { once: true }); + }); + } + requestTaskStore(request, sessionId) { + const taskStore = this._taskStore; + if (!taskStore) { + throw new Error("No task store configured"); + } + return { + createTask: async (taskParams) => { + if (!request) { + throw new Error("No request provided"); + } + return await taskStore.createTask(taskParams, request.id, { + method: request.method, + params: request.params + }, sessionId); + }, + getTask: async (taskId) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found"); + } + return task; + }, + storeTaskResult: async (taskId, status, result) => { + await taskStore.storeTaskResult(taskId, status, result, sessionId); + const task = await taskStore.getTask(taskId, sessionId); + if (task) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: task + }); + await this.notification(notification); + if (isTerminal(task.status)) { + this._cleanupTaskProgressHandler(taskId); + } + } + }, + getTaskResult: (taskId) => { + return taskStore.getTaskResult(taskId, sessionId); + }, + updateTaskStatus: async (taskId, status, statusMessage) => { + const task = await taskStore.getTask(taskId, sessionId); + if (!task) { + throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); + } + if (isTerminal(task.status)) { + throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); + } + await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); + const updatedTask = await taskStore.getTask(taskId, sessionId); + if (updatedTask) { + const notification = TaskStatusNotificationSchema.parse({ + method: "notifications/tasks/status", + params: updatedTask + }); + await this.notification(notification); + if (isTerminal(updatedTask.status)) { + this._cleanupTaskProgressHandler(taskId); + } + } + }, + listTasks: (cursor) => { + return taskStore.listTasks(cursor, sessionId); + } + }; + } + }; + function isPlainObject2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); + } + function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k2 = key; + const addValue = additional[k2]; + if (addValue === void 0) + continue; + const baseValue = result[k2]; + if (isPlainObject2(baseValue) && isPlainObject2(addValue)) { + result[k2] = { ...baseValue, ...addValue }; + } else { + result[k2] = addValue; + } + } + return result; + } + + // node_modules/@modelcontextprotocol/ext-apps/dist/src/app.js + init_v4(); + init_v4(); + var p = ((X) => typeof __require < "u" ? __require : typeof Proxy < "u" ? new Proxy(X, { get: (Y, Z) => (typeof __require < "u" ? __require : Y)[Z] }) : X)(function(X) { + if (typeof __require < "u") return __require.apply(this, arguments); + throw Error('Dynamic require of "' + X + '" is not supported'); + }); + var _ = class extends Protocol { + _registeredMethods = /* @__PURE__ */ new Set(); + _eventSlots = /* @__PURE__ */ new Map(); + onEventDispatch(X, Y) { + } + _ensureEventSlot(X) { + let Y = this._eventSlots.get(X); + if (!Y) { + let Z = this.eventSchemas[X]; + if (!Z) throw Error(`Unknown event: ${String(X)}`); + Y = { listeners: [] }, this._eventSlots.set(X, Y); + let $ = Z.shape.method.value; + this._registeredMethods.add($); + let D = Y; + super.setNotificationHandler(Z, (J) => { + let K = J.params; + this.onEventDispatch(X, K), D.onHandler?.(K); + for (let G of [...D.listeners]) G(K); + }); + } + return Y; + } + setEventHandler(X, Y) { + let Z = this._ensureEventSlot(X); + if (Z.onHandler && Y) console.warn(`[MCP Apps] on${String(X)} handler replaced. Use addEventListener("${String(X)}", \u2026) to add multiple listeners without replacing.`); + Z.onHandler = Y; + } + getEventHandler(X) { + return this._eventSlots.get(X)?.onHandler; + } + addEventListener(X, Y) { + this._ensureEventSlot(X).listeners.push(Y); + } + removeEventListener(X, Y) { + let Z = this._eventSlots.get(X); + if (!Z) return; + let $ = Z.listeners.indexOf(Y); + if ($ !== -1) Z.listeners.splice($, 1); + } + setRequestHandler = (X, Y) => { + this._assertMethodNotRegistered(X, "setRequestHandler"), super.setRequestHandler(X, Y); + }; + setNotificationHandler = (X, Y) => { + this._assertMethodNotRegistered(X, "setNotificationHandler"), super.setNotificationHandler(X, Y); + }; + warnIfRequestHandlerReplaced(X, Y, Z) { + if (Y && Z) console.warn(`[MCP Apps] ${X} handler replaced. Previous handler will no longer be called.`); + } + replaceRequestHandler = (X, Y) => { + let Z = X.shape.method.value; + this._registeredMethods.add(Z), super.setRequestHandler(X, Y); + }; + _assertMethodNotRegistered(X, Y) { + let Z = X.shape.method.value; + if (this._registeredMethods.has(Z)) throw Error(`Handler for "${Z}" already registered (via ${Y}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`); + this._registeredMethods.add(Z); + } + }; + var E = "2026-01-26"; + var O = "ui/notifications/tool-input-partial"; + var j = class { + eventTarget; + eventSource; + messageListener; + constructor(X = window.parent, Y) { + this.eventTarget = X; + this.eventSource = Y; + this.messageListener = (Z) => { + if (Y && Z.source !== this.eventSource) { + console.debug("Ignoring message from unknown source", Z); + return; + } + let $ = JSONRPCMessageSchema.safeParse(Z.data); + if ($.success) console.debug("Parsed message", $.data), this.onmessage?.($.data); + else if (Z.data?.jsonrpc !== "2.0") console.debug("Ignoring non-JSON-RPC message", $.error.message, Z); + else console.error("Failed to parse message", $.error.message, Z), this.onerror?.(Error("Invalid JSON-RPC message received: " + $.error.message)); + }; + } + async start() { + window.addEventListener("message", this.messageListener); + } + async send(X, Y) { + if (X.method !== O) console.debug("Sending message", X); + this.eventTarget.postMessage(X, "*"); + } + async close() { + window.removeEventListener("message", this.messageListener), this.onclose?.(); + } + onclose; + onerror; + onmessage; + sessionId; + setProtocolVersion; + }; + var g = external_exports.union([external_exports.literal("light"), external_exports.literal("dark")]).describe("Color theme preference for the host environment."); + var W = external_exports.union([external_exports.literal("inline"), external_exports.literal("fullscreen"), external_exports.literal("pip")]).describe("Display mode for UI presentation."); + var LQ = external_exports.union([external_exports.literal("--color-background-primary"), external_exports.literal("--color-background-secondary"), external_exports.literal("--color-background-tertiary"), external_exports.literal("--color-background-inverse"), external_exports.literal("--color-background-ghost"), external_exports.literal("--color-background-info"), external_exports.literal("--color-background-danger"), external_exports.literal("--color-background-success"), external_exports.literal("--color-background-warning"), external_exports.literal("--color-background-disabled"), external_exports.literal("--color-text-primary"), external_exports.literal("--color-text-secondary"), external_exports.literal("--color-text-tertiary"), external_exports.literal("--color-text-inverse"), external_exports.literal("--color-text-ghost"), external_exports.literal("--color-text-info"), external_exports.literal("--color-text-danger"), external_exports.literal("--color-text-success"), external_exports.literal("--color-text-warning"), external_exports.literal("--color-text-disabled"), external_exports.literal("--color-border-primary"), external_exports.literal("--color-border-secondary"), external_exports.literal("--color-border-tertiary"), external_exports.literal("--color-border-inverse"), external_exports.literal("--color-border-ghost"), external_exports.literal("--color-border-info"), external_exports.literal("--color-border-danger"), external_exports.literal("--color-border-success"), external_exports.literal("--color-border-warning"), external_exports.literal("--color-border-disabled"), external_exports.literal("--color-ring-primary"), external_exports.literal("--color-ring-secondary"), external_exports.literal("--color-ring-inverse"), external_exports.literal("--color-ring-info"), external_exports.literal("--color-ring-danger"), external_exports.literal("--color-ring-success"), external_exports.literal("--color-ring-warning"), external_exports.literal("--font-sans"), external_exports.literal("--font-mono"), external_exports.literal("--font-weight-normal"), external_exports.literal("--font-weight-medium"), external_exports.literal("--font-weight-semibold"), external_exports.literal("--font-weight-bold"), external_exports.literal("--font-text-xs-size"), external_exports.literal("--font-text-sm-size"), external_exports.literal("--font-text-md-size"), external_exports.literal("--font-text-lg-size"), external_exports.literal("--font-heading-xs-size"), external_exports.literal("--font-heading-sm-size"), external_exports.literal("--font-heading-md-size"), external_exports.literal("--font-heading-lg-size"), external_exports.literal("--font-heading-xl-size"), external_exports.literal("--font-heading-2xl-size"), external_exports.literal("--font-heading-3xl-size"), external_exports.literal("--font-text-xs-line-height"), external_exports.literal("--font-text-sm-line-height"), external_exports.literal("--font-text-md-line-height"), external_exports.literal("--font-text-lg-line-height"), external_exports.literal("--font-heading-xs-line-height"), external_exports.literal("--font-heading-sm-line-height"), external_exports.literal("--font-heading-md-line-height"), external_exports.literal("--font-heading-lg-line-height"), external_exports.literal("--font-heading-xl-line-height"), external_exports.literal("--font-heading-2xl-line-height"), external_exports.literal("--font-heading-3xl-line-height"), external_exports.literal("--border-radius-xs"), external_exports.literal("--border-radius-sm"), external_exports.literal("--border-radius-md"), external_exports.literal("--border-radius-lg"), external_exports.literal("--border-radius-xl"), external_exports.literal("--border-radius-full"), external_exports.literal("--border-width-regular"), external_exports.literal("--shadow-hairline"), external_exports.literal("--shadow-sm"), external_exports.literal("--shadow-md"), external_exports.literal("--shadow-lg")]).describe("CSS variable keys available to MCP apps for theming."); + var BQ = external_exports.record(LQ.describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`), external_exports.union([external_exports.string(), external_exports.undefined()]).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`); + var _Q = external_exports.object({ method: external_exports.literal("ui/open-link"), params: external_exports.object({ url: external_exports.string().describe("URL to open in the host's browser") }) }); + var I = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the host failed to open the URL (e.g., due to security policy).") }).passthrough(); + var F = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the download failed (e.g., user cancelled or host denied).") }).passthrough(); + var q = external_exports.object({ isError: external_exports.boolean().optional().describe("True if the host rejected or failed to deliver the message.") }).passthrough(); + var EQ = external_exports.object({ method: external_exports.literal("ui/notifications/sandbox-proxy-ready"), params: external_exports.object({}) }); + var L = external_exports.object({ connectDomains: external_exports.array(external_exports.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). + +- Maps to CSP \`connect-src\` directive +- Empty or omitted \u2192 no network connections (secure default)`), resourceDomains: external_exports.array(external_exports.string()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted \u2192 no network resources (secure default)"), frameDomains: external_exports.array(external_exports.string()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted \u2192 no nested iframes allowed (`frame-src 'none'`)"), baseUriDomains: external_exports.array(external_exports.string()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted \u2192 only same origin allowed (`base-uri 'self'`)") }); + var B = external_exports.object({ camera: external_exports.object({}).optional().describe("Request camera access.\n\nMaps to Permission Policy `camera` feature."), microphone: external_exports.object({}).optional().describe("Request microphone access.\n\nMaps to Permission Policy `microphone` feature."), geolocation: external_exports.object({}).optional().describe("Request geolocation access.\n\nMaps to Permission Policy `geolocation` feature."), clipboardWrite: external_exports.object({}).optional().describe("Request clipboard write access.\n\nMaps to Permission Policy `clipboard-write` feature.") }); + var OQ = external_exports.object({ method: external_exports.literal("ui/notifications/size-changed"), params: external_exports.object({ width: external_exports.number().optional().describe("New width in pixels."), height: external_exports.number().optional().describe("New height in pixels.") }) }); + var P = external_exports.object({ method: external_exports.literal("ui/notifications/tool-input"), params: external_exports.object({ arguments: external_exports.record(external_exports.string(), external_exports.unknown().describe("Complete tool call arguments as key-value pairs.")).optional().describe("Complete tool call arguments as key-value pairs.") }) }); + var w = external_exports.object({ method: external_exports.literal("ui/notifications/tool-input-partial"), params: external_exports.object({ arguments: external_exports.record(external_exports.string(), external_exports.unknown().describe("Partial tool call arguments (incomplete, may change).")).optional().describe("Partial tool call arguments (incomplete, may change).") }) }); + var A = external_exports.object({ method: external_exports.literal("ui/notifications/tool-cancelled"), params: external_exports.object({ reason: external_exports.string().optional().describe('Optional reason for the cancellation (e.g., "user action", "timeout").') }) }); + var v = external_exports.object({ fonts: external_exports.string().optional() }); + var f = external_exports.object({ variables: BQ.optional().describe("CSS variables for theming the app."), css: v.optional().describe("CSS blocks that apps can inject.") }); + var R = external_exports.object({ method: external_exports.literal("ui/resource-teardown"), params: external_exports.object({}) }); + var zQ = external_exports.record(external_exports.string(), external_exports.unknown()); + var z = external_exports.object({ text: external_exports.object({}).optional().describe("Host supports text content blocks."), image: external_exports.object({}).optional().describe("Host supports image content blocks."), audio: external_exports.object({}).optional().describe("Host supports audio content blocks."), resource: external_exports.object({}).optional().describe("Host supports resource content blocks."), resourceLink: external_exports.object({}).optional().describe("Host supports resource link content blocks."), structuredContent: external_exports.object({}).optional().describe("Host supports structured content.") }); + var IQ = external_exports.object({ method: external_exports.literal("ui/notifications/request-teardown"), params: external_exports.object({}).optional() }); + var u = external_exports.object({ experimental: external_exports.record(external_exports.string(), external_exports.record(external_exports.string(), external_exports.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."), openLinks: external_exports.object({}).optional().describe("Host supports opening external URLs."), downloadFile: external_exports.object({}).optional().describe("Host supports file downloads via ui/download-file."), serverTools: external_exports.object({ listChanged: external_exports.boolean().optional().describe("Host supports tools/list_changed notifications.") }).optional().describe("Host can proxy tool calls to the MCP server."), serverResources: external_exports.object({ listChanged: external_exports.boolean().optional().describe("Host supports resources/list_changed notifications.") }).optional().describe("Host can proxy resource reads to the MCP server."), logging: external_exports.object({}).optional().describe("Host accepts log messages."), sandbox: external_exports.object({ permissions: B.optional().describe("Permissions granted by the host (camera, microphone, geolocation)."), csp: L.optional().describe("CSP domains approved by the host.") }).optional().describe("Sandbox configuration applied by the host."), updateModelContext: z.optional().describe("Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns."), message: z.optional().describe("Host supports receiving content messages (ui/message) from the view."), sampling: external_exports.object({ tools: external_exports.object({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.") }).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.") }); + var d = external_exports.object({ experimental: external_exports.record(external_exports.string(), external_exports.record(external_exports.string(), external_exports.any()).describe("Experimental features keyed by identifier.")).optional().describe("Experimental features keyed by identifier."), tools: external_exports.object({ listChanged: external_exports.boolean().optional().describe("App supports tools/list_changed notifications.") }).optional().describe("App exposes MCP-style tools that the host can call."), availableDisplayModes: external_exports.array(W).optional().describe("Display modes the app supports.") }); + var FQ = external_exports.object({ method: external_exports.literal("ui/notifications/initialized"), params: external_exports.object({}).optional() }); + var qQ = external_exports.object({ csp: L.optional().describe("Content Security Policy configuration for UI resources."), permissions: B.optional().describe("Sandbox permissions requested by the UI resource."), domain: external_exports.string().optional().describe(`Dedicated origin for view sandbox. + +Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. + +**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: +- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) +- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) + +If omitted, host uses default sandbox origin (typically per-conversation).`), prefersBorder: external_exports.boolean().optional().describe(`Visual boundary preference - true if view prefers a visible border. + +Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. + +- \`true\`: request visible border + background +- \`false\`: request no visible border + background +- omitted: host decides border`) }); + var PQ = external_exports.object({ method: external_exports.literal("ui/request-display-mode"), params: external_exports.object({ mode: W.describe("The display mode being requested.") }) }); + var U = external_exports.object({ mode: W.describe("The display mode that was actually set. May differ from requested if not supported.") }).passthrough(); + var h = external_exports.union([external_exports.literal("model"), external_exports.literal("app")]).describe("Tool visibility scope - who can access the tool."); + var wQ = external_exports.object({ resourceUri: external_exports.string().optional(), visibility: external_exports.array(h).optional().describe(`Who can access this tool. Default: ["model", "app"] +- "model": Tool visible to and callable by the agent +- "app": Tool callable by the app from this server only`), csp: external_exports.never().optional(), permissions: external_exports.never().optional() }); + var YX = external_exports.object({ mimeTypes: external_exports.array(external_exports.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.') }); + var AQ = external_exports.object({ method: external_exports.literal("ui/download-file"), params: external_exports.object({ contents: external_exports.array(external_exports.union([EmbeddedResourceSchema, ResourceLinkSchema])).describe("Resource contents to download \u2014 embedded (inline data) or linked (host fetches). Uses standard MCP resource types.") }) }); + var RQ = external_exports.object({ method: external_exports.literal("ui/message"), params: external_exports.object({ role: external_exports.literal("user").describe('Message role, currently only "user" is supported.'), content: external_exports.array(ContentBlockSchema).describe("Message content blocks (text, image, etc.).") }) }); + var UQ = external_exports.object({ method: external_exports.literal("ui/notifications/sandbox-resource-ready"), params: external_exports.object({ html: external_exports.string().describe("HTML content to load into the inner iframe."), sandbox: external_exports.string().optional().describe("Optional override for the inner iframe's sandbox attribute."), csp: L.optional().describe("CSP configuration from resource metadata."), permissions: B.optional().describe("Sandbox permissions from resource metadata.") }) }); + var H = external_exports.object({ method: external_exports.literal("ui/notifications/tool-result"), params: CallToolResultSchema.describe("Standard MCP tool execution result.") }); + var T = external_exports.object({ toolInfo: external_exports.object({ id: RequestIdSchema.optional().describe("JSON-RPC id of the tools/call request."), tool: ToolSchema.describe("Tool definition including name, inputSchema, etc.") }).optional().describe("Metadata of the tool call that instantiated this App."), theme: g.optional().describe("Current color theme preference."), styles: f.optional().describe("Style configuration for theming the app."), displayMode: W.optional().describe("How the UI is currently displayed."), availableDisplayModes: external_exports.array(W).optional().describe("Display modes the host supports."), containerDimensions: external_exports.union([external_exports.object({ height: external_exports.number().describe("Fixed container height in pixels.") }), external_exports.object({ maxHeight: external_exports.union([external_exports.number(), external_exports.undefined()]).optional().describe("Maximum container height in pixels.") })]).and(external_exports.union([external_exports.object({ width: external_exports.number().describe("Fixed container width in pixels.") }), external_exports.object({ maxWidth: external_exports.union([external_exports.number(), external_exports.undefined()]).optional().describe("Maximum container width in pixels.") })])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other +container holding the app. Specify either width or maxWidth, and either height or maxHeight.`), locale: external_exports.string().optional().describe("User's language and region preference in BCP 47 format."), timeZone: external_exports.string().optional().describe("User's timezone in IANA format."), userAgent: external_exports.string().optional().describe("Host application identifier."), platform: external_exports.union([external_exports.literal("web"), external_exports.literal("desktop"), external_exports.literal("mobile")]).optional().describe("Platform type for responsive design decisions."), deviceCapabilities: external_exports.object({ touch: external_exports.boolean().optional().describe("Whether the device supports touch input."), hover: external_exports.boolean().optional().describe("Whether the device supports hover interactions.") }).optional().describe("Device input capabilities."), safeAreaInsets: external_exports.object({ top: external_exports.number().describe("Top safe area inset in pixels."), right: external_exports.number().describe("Right safe area inset in pixels."), bottom: external_exports.number().describe("Bottom safe area inset in pixels."), left: external_exports.number().describe("Left safe area inset in pixels.") }).optional().describe("Mobile safe area boundaries in pixels.") }).passthrough(); + var M = external_exports.object({ method: external_exports.literal("ui/notifications/host-context-changed"), params: T.describe("Partial context update containing only changed fields.") }); + var HQ = external_exports.object({ method: external_exports.literal("ui/update-model-context"), params: external_exports.object({ content: external_exports.array(ContentBlockSchema).optional().describe("Context content blocks (text, image, etc.)."), structuredContent: external_exports.record(external_exports.string(), external_exports.unknown().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.") }) }); + var TQ = external_exports.object({ method: external_exports.literal("ui/initialize"), params: external_exports.object({ appInfo: ImplementationSchema.describe("App identification (name and version)."), appCapabilities: d.describe("Features and capabilities this app provides."), protocolVersion: external_exports.string().describe("Protocol version this app supports.") }) }); + var C = external_exports.object({ protocolVersion: external_exports.string().describe('Negotiated protocol version string (e.g., "2025-11-21").'), hostInfo: ImplementationSchema.describe("Host application identification and version."), hostCapabilities: u.describe("Features and capabilities provided by the host."), hostContext: T.describe("Rich context about the host environment.") }).passthrough(); + var MQ = { target: "draft-2020-12" }; + async function k(X, Y) { + let Z = X["~standard"]; + if (Z.jsonSchema) return Z.jsonSchema[Y](MQ); + if (Z.vendor === "zod") { + let { z: $ } = await Promise.resolve().then(() => (init_v4(), v4_exports)); + return $.toJSONSchema(X, { io: Y }); + } + throw Error(`Schema (vendor: ${Z.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`); + } + async function b(X, Y, Z = "") { + let $ = await X["~standard"].validate(Y); + if ($.issues) { + let D = $.issues.map((J) => { + let K = J.path?.map((G) => typeof G === "object" ? G.key : G).join("."); + return K ? `${K}: ${J.message}` : J.message; + }).join("; "); + throw Error(Z + D); + } + return $.value; + } + var i = class _i extends _ { + _appInfo; + _capabilities; + options; + _hostCapabilities; + _hostInfo; + _hostContext; + _registeredTools = {}; + _initializedSent = false; + _assertInitialized(X) { + if (this._initializedSent) return; + let Y = `[ext-apps] App.${X}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`; + if (this.options?.strict) throw Error(Y); + console.warn(`${Y}. This will throw in a future release.`); + } + eventSchemas = { toolinput: P, toolinputpartial: w, toolresult: H, toolcancelled: A, hostcontextchanged: M }; + static ONE_SHOT_EVENTS = /* @__PURE__ */ new Set(["toolinput", "toolinputpartial", "toolresult", "toolcancelled"]); + _everHadListener = /* @__PURE__ */ new Set(); + _assertHandlerTiming(X) { + if (!_i.ONE_SHOT_EVENTS.has(X) || this._everHadListener.has(X)) return; + if (this._everHadListener.add(X), !this._initializedSent) return; + let Y = `[ext-apps] "${String(X)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`; + if (this.options?.strict) throw Error(Y); + console.warn(Y); + } + setEventHandler(X, Y) { + if (Y) this._assertHandlerTiming(X); + super.setEventHandler(X, Y); + } + addEventListener(X, Y) { + this._assertHandlerTiming(X), super.addEventListener(X, Y); + } + onEventDispatch(X, Y) { + if (X === "hostcontextchanged") this._hostContext = { ...this._hostContext, ...Y }; + } + constructor(X, Y = {}, Z = { autoResize: true }) { + super(Z); + this._appInfo = X; + this._capabilities = Y; + this.options = Z; + if (!Z.allowUnsafeEval) external_exports.config({ jitless: true }); + this.setRequestHandler(PingRequestSchema, ($) => { + return console.log("Received ping:", $.params), {}; + }), this.setEventHandler("hostcontextchanged", void 0); + } + registerCapabilities(X) { + if (this.transport) throw Error("Cannot register capabilities after transport is established"); + this._capabilities = mergeCapabilities(this._capabilities, X); + } + registerTool(X, Y, Z) { + if (this._registeredTools[X]) throw Error(`Tool ${X} is already registered`); + let $ = this, D = () => { + if ($._initializedSent && $._capabilities.tools?.listChanged) $.sendToolListChanged(); + }, J = Y.inputSchema !== void 0, K = { title: Y.title, description: Y.description, inputSchema: Y.inputSchema, outputSchema: Y.outputSchema, annotations: Y.annotations, _meta: Y._meta, enabled: true, enable() { + this.enabled = true, D(); + }, disable() { + this.enabled = false, D(); + }, update(G) { + Object.assign(this, G), D(); + }, remove() { + if ($._registeredTools[X] !== K) return; + delete $._registeredTools[X], D(); + }, handler: async (G, N) => { + if (!K.enabled) throw Error(`Tool ${X} is disabled`); + let V; + if (J) { + let S = K.inputSchema, m = S ? await b(S, G ?? {}, `Invalid input for tool ${X}: `) : G ?? {}; + V = await Z(m, N); + } else V = await Z(N); + if (K.outputSchema && !V.isError) V.structuredContent = await b(K.outputSchema, V.structuredContent, `Invalid output for tool ${X}: `); + return V; + } }; + if (this._registeredTools[X] = K, !this._capabilities.tools && !this.transport) this.registerCapabilities({ tools: { listChanged: true } }); + return this.ensureToolHandlersInitialized(), D(), K; + } + _toolHandlersInitialized = false; + ensureToolHandlersInitialized() { + if (this._toolHandlersInitialized) return; + this._toolHandlersInitialized = true, this.oncalltool = async (X, Y) => { + let Z = this._registeredTools[X.name]; + if (!Z) throw Error(`Tool ${X.name} not found`); + return Z.handler(X.arguments, Y); + }, this.onlisttools = async (X, Y) => { + return { tools: await Promise.all(Object.entries(this._registeredTools).filter(([$, D]) => D.enabled).map(async ([$, D]) => { + let J = { name: $, title: D.title, description: D.description, inputSchema: D.inputSchema ? await k(D.inputSchema, "input") : { type: "object", properties: {} } }; + if (D.outputSchema) J.outputSchema = await k(D.outputSchema, "output"); + if (D.annotations) J.annotations = D.annotations; + if (D._meta) J._meta = D._meta; + return J; + })) }; + }; + } + async sendToolListChanged(X = {}) { + this._assertInitialized("sendToolListChanged"), await this.notification({ method: "notifications/tools/list_changed", params: X }); + } + getHostCapabilities() { + return this._hostCapabilities; + } + getHostVersion() { + return this._hostInfo; + } + getHostContext() { + return this._hostContext; + } + get ontoolinput() { + return this.getEventHandler("toolinput"); + } + set ontoolinput(X) { + this.setEventHandler("toolinput", X); + } + get ontoolinputpartial() { + return this.getEventHandler("toolinputpartial"); + } + set ontoolinputpartial(X) { + this.setEventHandler("toolinputpartial", X); + } + get ontoolresult() { + return this.getEventHandler("toolresult"); + } + set ontoolresult(X) { + this.setEventHandler("toolresult", X); + } + get ontoolcancelled() { + return this.getEventHandler("toolcancelled"); + } + set ontoolcancelled(X) { + this.setEventHandler("toolcancelled", X); + } + get onhostcontextchanged() { + return this.getEventHandler("hostcontextchanged"); + } + set onhostcontextchanged(X) { + this.setEventHandler("hostcontextchanged", X); + } + _onteardown; + get onteardown() { + return this._onteardown; + } + set onteardown(X) { + this.warnIfRequestHandlerReplaced("onteardown", this._onteardown, X), this._onteardown = X, this.replaceRequestHandler(R, (Y, Z) => { + if (!this._onteardown) throw Error("No onteardown handler set"); + return this._onteardown(Y.params, Z); + }); + } + _oncalltool; + get oncalltool() { + return this._oncalltool; + } + set oncalltool(X) { + this.warnIfRequestHandlerReplaced("oncalltool", this._oncalltool, X), this._oncalltool = X, this.replaceRequestHandler(CallToolRequestSchema, (Y, Z) => { + if (!this._oncalltool) throw Error("No oncalltool handler set"); + return this._oncalltool(Y.params, Z); + }); + } + _onlisttools; + get onlisttools() { + return this._onlisttools; + } + set onlisttools(X) { + this.warnIfRequestHandlerReplaced("onlisttools", this._onlisttools, X), this._onlisttools = X, this.replaceRequestHandler(ListToolsRequestSchema, (Y, Z) => { + if (!this._onlisttools) throw Error("No onlisttools handler set"); + return this._onlisttools(Y.params, Z); + }); + } + assertCapabilityForMethod(X) { + switch (X) { + case "sampling/createMessage": + if (!this._hostCapabilities?.sampling) throw Error(`Host does not support sampling (required for ${X})`); + break; + } + } + assertRequestHandlerCapability(X) { + switch (X) { + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) throw Error(`Client does not support tool capability (required for ${X})`); + return; + case "ping": + case "ui/resource-teardown": + return; + default: + throw Error(`No handler for method ${X} registered`); + } + } + assertNotificationCapability(X) { + } + assertTaskCapability(X) { + throw Error("Tasks are not supported in MCP Apps"); + } + assertTaskHandlerCapability(X) { + throw Error("Task handlers are not supported in MCP Apps"); + } + async callServerTool(X, Y) { + if (this._assertInitialized("callServerTool"), typeof X === "string") throw Error(`callServerTool() expects an object as its first argument, but received a string ("${X}"). Did you mean: callServerTool({ name: "${X}", arguments: { ... } })?`); + return await this.request({ method: "tools/call", params: X }, CallToolResultSchema, { onprogress: () => { + }, resetTimeoutOnProgress: true, ...Y }); + } + async readServerResource(X, Y) { + return this._assertInitialized("readServerResource"), await this.request({ method: "resources/read", params: X }, ReadResourceResultSchema, Y); + } + async listServerResources(X, Y) { + return this._assertInitialized("listServerResources"), await this.request({ method: "resources/list", params: X }, ListResourcesResultSchema, Y); + } + async createSamplingMessage(X, Y) { + this._assertInitialized("createSamplingMessage"); + let Z = X.tools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema; + return await this.request({ method: "sampling/createMessage", params: X }, Z, Y); + } + sendMessage(X, Y) { + return this._assertInitialized("sendMessage"), this.request({ method: "ui/message", params: X }, q, Y); + } + sendLog(X) { + return this.notification({ method: "notifications/message", params: X }); + } + updateModelContext(X, Y) { + return this._assertInitialized("updateModelContext"), this.request({ method: "ui/update-model-context", params: X }, EmptyResultSchema, Y); + } + openLink(X, Y) { + return this._assertInitialized("openLink"), this.request({ method: "ui/open-link", params: X }, I, Y); + } + sendOpenLink = this.openLink; + downloadFile(X, Y) { + return this._assertInitialized("downloadFile"), this.request({ method: "ui/download-file", params: X }, F, Y); + } + requestTeardown(X = {}) { + return this.notification({ method: "ui/notifications/request-teardown", params: X }); + } + requestDisplayMode(X, Y) { + return this._assertInitialized("requestDisplayMode"), this.request({ method: "ui/request-display-mode", params: X }, U, Y); + } + sendSizeChanged(X) { + return this.notification({ method: "ui/notifications/size-changed", params: X }); + } + setupSizeChangedNotifications() { + let X = false, Y = 0, Z = 0, $ = () => { + if (X) return; + X = true, requestAnimationFrame(() => { + X = false; + let J = document.documentElement, K = J.style.height; + J.style.height = "max-content"; + let G = Math.ceil(J.getBoundingClientRect().height); + J.style.height = K; + let N = Math.ceil(window.innerWidth); + if (N !== Y || G !== Z) Y = N, Z = G, this.sendSizeChanged({ width: N, height: G }); + }); + }; + $(); + let D = new ResizeObserver($); + return D.observe(document.documentElement), D.observe(document.body), () => D.disconnect(); + } + async connect(X = new j(window.parent, window.parent), Y) { + if (this.transport) throw Error("App is already connected. Call close() before connecting again."); + this._initializedSent = false, await super.connect(X); + try { + let Z = await this.request({ method: "ui/initialize", params: { appCapabilities: this._capabilities, appInfo: this._appInfo, protocolVersion: E } }, C, Y); + if (Z === void 0) throw Error(`Server sent invalid initialize result: ${Z}`); + if (this._hostCapabilities = Z.hostCapabilities, this._hostInfo = Z.hostInfo, this._hostContext = Z.hostContext, await this.notification({ method: "ui/notifications/initialized" }), this._initializedSent = true, this.options?.autoResize) this.setupSizeChangedNotifications(); + } catch (Z) { + throw this.close(), Z; + } + } + }; + + // src/ui-core/tokens.ts + var TOKEN_CSS = ` +:root, [data-theme="light"] { + color-scheme: light; + /* \u6587\u5B57\u56DB\u6863\uFF08dsw label-primary/secondary/tertiary/caption\uFF1B + caption \u65E0\u72EC\u7ACB\u5BBF\u4E3B\u53D8\u91CF \u2192 tertiary \u540C\u6863 + \u5B57\u9762\u515C\u5E95\u533A\u5206\uFF09 */ + --at-label-primary: var(--color-text-primary, var(--foreground, #1a2233)); + --at-label-secondary: var(--color-text-secondary, var(--muted-foreground, #3d4a5c)); + --at-label-tertiary: var(--color-text-tertiary, var(--muted-foreground, #8a94a6)); + --at-label-caption: var(--color-text-tertiary, #9aa3b2); + /* \u80CC\u666F\u4E24\u6863\uFF08dsw specific-menu / bg-layer-2\uFF09 */ + --at-bg-menu: var(--color-background-secondary, var(--muted, #f7f8fa)); + --at-bg-layer-2: var(--color-background-primary, var(--card, #ffffff)); + /* \u63CF\u8FB9\u4E09\u6863\uFF08dsw border-l1/l2/l3\uFF1B\u5BBF\u4E3B\u5355\u6863 --border \u2192 \u4E09\u6863\u900F\u660E\u5EA6\u6D3E\u751F\uFF09 */ + --at-border-l1: var(--color-border-primary, var(--border, rgba(16, 24, 40, 0.08))); + --at-border-l2: var(--color-border-tertiary, var(--border, #e3e6eb)); + --at-border-l3: var(--color-border-secondary, var(--border, #c9cfd8)); + /* \u72B6\u6001\u70B9\u4E94\u7C7B\u8272\uFF08ongoing/idle/done/warning \u2192 --green/\u7070/--blue/--yellow \u6216\u81EA\u7ED8\uFF09 */ + --at-state-ongoing: var(--color-text-success, var(--green, #12a675)); + --at-state-error: var(--color-text-danger, var(--red, #e5484d)); + --at-state-idle: var(--color-text-disabled, #98a2b3); + --at-state-warning: var(--color-text-warning, var(--yellow, #f59e0b)); + --at-state-done: var(--color-text-info, var(--blue, #3e7bfa)); + /* \u4E1A\u52A1\u4E3B\u8272\uFF08dsw state-business-primary\uFF1A\u5F53\u524D\u4F1A\u8BDD\u9AD8\u4EAE/info Tag\uFF09 */ + --at-business: var(--color-text-info, var(--primary, #3e7bfa)); + /* \u9519\u8BEF\u6587\u672C\uFF08dsw state-error-primary\uFF09 */ + --at-error-text: var(--color-text-danger, var(--red, var(--destructive, #d93036))); + /* advisory \u8B66\u544A\u6587\u672C\u8272\uFF08\u6DF1\u7425\u73C0\u4FDD\u8BC1 11px \u5C0F\u5B57\u5BF9\u6BD4\u5EA6\uFF09 */ + --at-warning-text: var(--color-text-warning, var(--yellow, #b45309)); + /* \u9634\u5F71\u4E24\u6863\uFF08dsw elevation-prominent / elevation-panel\uFF09 */ + --at-shadow-prominent: var(--shadow-lg, 0 8px 28px rgba(16, 24, 40, 0.16)); + --at-shadow-panel: var(--shadow-md, 0 4px 16px rgba(16, 24, 40, 0.12)); + /* \u6EDA\u52A8\u6761\uFF08dsh scrollbar \u4EE4\u724C\u81EA\u7ED8\uFF09 */ + --at-scrollbar-thumb: color-mix(in srgb, var(--at-label-tertiary) 40%, transparent); + --at-scrollbar-thumb-hover: color-mix(in srgb, var(--at-label-tertiary) 60%, transparent); + /* \u5B57\u4F53\uFF08\u4E0D\u5F15\u5916\u90E8\u5B57\u4F53\uFF0C\u8DDF\u968F\u5BBF\u4E3B UI \u5B57\u4F53\u6808\uFF09 */ + --at-font: var(--font-sans, -apple-system, "PingFang SC", "Segoe UI", sans-serif); +} +[data-theme="dark"] { + color-scheme: dark; + --at-label-primary: var(--color-text-primary, var(--foreground, #e8eaf0)); + --at-label-secondary: var(--color-text-secondary, var(--muted-foreground, #c0c6d2)); + --at-label-tertiary: var(--color-text-tertiary, var(--muted-foreground, #8d95a3)); + --at-label-caption: var(--color-text-tertiary, #7d8593); + --at-bg-menu: var(--color-background-secondary, var(--muted, #1b1e24)); + --at-bg-layer-2: var(--color-background-primary, var(--card, #23262d)); + --at-border-l1: var(--color-border-primary, var(--border, rgba(255, 255, 255, 0.08))); + --at-border-l2: var(--color-border-tertiary, var(--border, #333842)); + --at-border-l3: var(--color-border-secondary, var(--border, #434a56)); + --at-state-ongoing: var(--color-text-success, var(--green, #2fbf8f)); + --at-state-error: var(--color-text-danger, var(--red, #ff6b6e)); + --at-state-idle: var(--color-text-disabled, #7d8593); + --at-state-warning: var(--color-text-warning, var(--yellow, #ffb454)); + --at-state-done: var(--color-text-info, var(--blue, #6c9cff)); + --at-business: var(--color-text-info, var(--primary, #6c9cff)); + --at-error-text: var(--color-text-danger, var(--red, var(--destructive, #ff8a8d))); + /* advisory \u8B66\u544A\u6587\u672C\u8272 */ + --at-warning-text: var(--color-text-warning, var(--yellow, #ffb454)); + --at-shadow-prominent: var(--shadow-lg, 0 8px 28px rgba(0, 0, 0, 0.5)); + --at-shadow-panel: var(--shadow-md, 0 4px 16px rgba(0, 0, 0, 0.4)); +} +`; + + // src/ui-core/css.ts + var COMPONENT_CSS = ` +${TOKEN_CSS} +* { box-sizing: border-box; } +.at-root { + font-family: var(--at-font); + font-size: 13px; + line-height: 1.5; + color: var(--at-label-primary); + width: 100%; +} +/* \xA710.3 \u9762\u677F\uFF1A\u5BBD min(500px, \u5BB9\u5668\u221232px)\uFF1B\u7D27\u51D1 min(320px,\u2026)\uFF1B\u6700\u5927\u9AD8 min(680px, \u89C6\u53E3\u221232px)\uFF1B + \u5706\u89D2 12\uFF1Bpadding 8px 2px 0\uFF1Bflex column\uFF1Boverflow hidden\uFF1Belevation-prominent \u9634\u5F71\uFF1B + border-l1 \u63CF\u8FB9\uFF08stroke \u7B49\u4EF7\uFF0C\u65E0 border\uFF09 */ +.team-panel { + width: min(500px, 100% - 32px); + max-height: min(680px, 100vh - 32px); + border-radius: 12px; + box-shadow: var(--at-shadow-prominent); + outline: 0.5px solid var(--at-border-l1); + background: var(--at-bg-menu); + padding: 8px 2px 0; + display: flex; + flex-direction: column; + overflow: hidden; + position: relative; +} +.team-panel.compact { width: min(320px, 100% - 32px); } +/* \xA710.3 body\uFF1Aoverflow-y auto\uFF1Bscrollbar-gutter stable\uFF1Bpadding 0 9px 16px 14px */ +.panel-body { + overflow-y: auto; + scrollbar-gutter: stable; + padding: 0 9px 16px 14px; + flex: auto; + min-height: 0; + scrollbar-color: var(--at-scrollbar-thumb) transparent; +} +.panel-body::-webkit-scrollbar { width: 8px; } +.panel-body::-webkit-scrollbar-thumb { + background: var(--at-scrollbar-thumb); + border-radius: 4px; +} +.panel-body::-webkit-scrollbar-thumb:hover { background: var(--at-scrollbar-thumb-hover); } +/* \xA710.5 \u8282\u6807\u9898\uFF1A13px/500\uFF0Cmargin 16px 0 8px 4px\uFF08\u9996\u8282 top 8px\uFF09\uFF0Cgap 8\uFF1B + count 12px/16px tabular-nums caption \u8272 */ +.panel-body h3 { + font-size: 13px; + font-weight: 500; + color: var(--at-label-primary); + margin: 16px 0 8px 4px; + display: flex; + align-items: center; + gap: 8px; +} +.panel-body section:first-of-type h3 { margin-top: 8px; } +h3 .count { + font-size: 12px; + line-height: 16px; + font-weight: 400; + color: var(--at-label-caption); + font-variant-numeric: tabular-nums; +} +/* \xA710.5 \u82B1\u540D\u518C\u7F51\u683C\uFF1A\u53CC\u5217 minmax(0,1fr) gap 8\uFF1B\u7D27\u51D1\u5355\u5217 */ +.roster { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } +.compact .roster { grid-template-columns: minmax(0, 1fr); } +/* \xA710.5 \u6210\u5458\u5361\uFF1A\u5706\u89D2 8\uFF1Bpadding 10px 12px\uFF1Bgap 8\uFF1Bbg-layer-2\uFF1B\u63CF\u8FB9 border-l2\uFF08stroke \u7B49\u4EF7\uFF09\uFF1B + \u6587\u5B57\u5DE6\u5BF9\u9F50\uFF1Bflex \u9876\u5BF9\u9F50\uFF1Bhover\uFF08\u975E\u7981\u7528\uFF09border-l3 + elevation-panel\uFF1Bdisabled cursor default */ +.member { + border-radius: 8px; + padding: 10px 12px; + gap: 8px; + background: var(--at-bg-layer-2); + box-shadow: 0 0 0 0.5px var(--at-border-l2); + border: none; + text-align: left; + display: flex; + align-items: flex-start; + font: inherit; + color: inherit; + min-width: 0; + cursor: pointer; +} +.member:disabled { cursor: default; } +.member:not(:disabled):hover, +.member:not(:disabled):focus-visible { + box-shadow: 0 0 0 0.5px var(--at-border-l3), var(--at-shadow-panel); +} +/* \u5F53\u524D\u4F1A\u8BDD\u9AD8\u4EAE\uFF08\u4EC5 members>1\uFF09\uFF1Abusiness 40% \u6DF7\u8272\u63CF\u8FB9 + inset 1px \u5185\u73AF */ +.member.current { + box-shadow: 0 0 0 0.5px color-mix(in srgb, var(--at-business) 40%, transparent), + inset 0 0 0 1px color-mix(in srgb, var(--at-business) 40%, transparent); +} +/* \u540D\u5B57/\u6B21\u884C\u6587\u672C\u5217\uFF08\xA710.5 memberText\uFF1Acolumn\uFF0Cmin-width 0 \u4F9B ellipsis\uFF09 */ +.member .member-text { display: flex; flex-direction: column; min-width: 0; gap: 2px; } +.member .row1 { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 100%; } +/* \u72B6\u6001\u70B9\u5BB9\u5668\uFF1A1lh \u9AD8\u5782\u76F4\u5BF9\u9F50\uFF08\xA710.5 memberDot\uFF09 */ +.member-dot { flex: none; align-items: center; height: 1lh; display: inline-flex; } +.member .name { + font-weight: 500; + color: var(--at-label-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; +} +.member .sub { + font-size: 11px; + color: var(--at-label-tertiary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100%; +} +/* hover/focus \u624D\u663E\u793A\u300C \xB7 \u6A21\u578B: model\u300D\uFF08\xA710.5/V06\uFF09 */ +.member .model { display: none; } +.member:hover .model, +.member:focus-visible .model { display: inline; } +.member .diagnostic { + font-size: 11px; + color: var(--at-error-text); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 100%; +} +/* \u5F53\u524D\u4F1A\u8BDD Tag\uFF0810px/15px\uFF0Cpadding 0 4px\uFF0Cinfo tone\uFF09 */ +.current-tag { + font-size: 10px; + line-height: 15px; + padding: 0 4px; + border-radius: 4px; + background: color-mix(in srgb, var(--at-business) 16%, transparent); + color: var(--at-business); + flex: none; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +/* 0.4.0 \u6CE8\u9500\u6210\u5458\u5361/\u9F7F\u8F6E\u4E0E\u8BBE\u7F6E\u5F39\u7A97\u6837\u5F0F\uFF08member-card\u3001member-gear\u3001settings \u7CFB\u5217\u3001 + source-badge\u3001modal-select\uFF09\uFF1A\u6210\u5458\u6A21\u578B\u552F\u4E00\u8DEF\u7EBF = \u6BCF\u8F6E\u8DDF\u968F Lead\uFF0C\u9762\u677F\u6062\u590D\u96F6\u53D8\u66F4\u901A\u9053\u3002 */ +/* \u72B6\u6001\u70B9\uFF1A\u76F4\u5F84\u4E00\u81F4 8px\uFF08V06\uFF09 */ +.dot { width: 8px; height: 8px; border-radius: 50%; flex: none; display: inline-block; } +.dot.ongoing { background: var(--at-state-ongoing); } +.dot.error { background: var(--at-state-error); } +.dot.idle { background: var(--at-state-idle); } +.dot.warning { background: var(--at-state-warning); } +.dot.done { background: var(--at-state-done); } +/* inactive \u4EBA\u5F62\u56FE\u6807\uFF1A14px tertiary\uFF08\xA710.5/V06\uFF09 */ +.icon-user { width: 14px; height: 14px; flex: none; color: var(--at-label-tertiary); display: inline-flex; } +/* \xA710.4 \u901A\u77E5\u6761\uFF1Aflex gap 6 padding 9 \u5B57\u53F7 12\uFF1Berror = \u9519\u8BEF\u8272\uFF1B\u6309\u5E8F\u6E32\u67D3 */ +.notice, .error-bar { + display: flex; + align-items: center; + gap: 6px; + padding: 9px; + font-size: 12px; +} +.error-bar { color: var(--at-error-text); } +.notice { color: var(--at-label-secondary); } +/* \xA710.6 \u4EFB\u52A1\u677F\uFF1A\u7A7A\u677F\u6BB5\u843D 12px tertiary margin 16px 0 0 4px\uFF1B\u5217\u8868 flex column gap 7 */ +.empty-notice { font-size: 12px; color: var(--at-label-tertiary); margin: 16px 0 0 4px; } +.tasks { display: flex; flex-direction: column; gap: 7px; } +/* \u4EFB\u52A1\u5361\uFF1Aborder 0.5px border-l2\uFF1B\u5706\u89D2 9\uFF1Bpadding 11px 13px\uFF1Bbg-layer-2 */ +article.task { + border: 0.5px solid var(--at-border-l2); + border-radius: 9px; + padding: 11px 13px; + background: var(--at-bg-layer-2); +} +.task .title-row { display: flex; align-items: center; gap: 8px; } +.task strong { font-size: 13px; font-weight: 500; line-height: 1.4; color: var(--at-label-primary); } +/* \u72B6\u6001\u5FBD\u6807\u53F3\u5BF9\u9F50 11px gap 6 */ +.task .task-state { + margin-left: auto; + font-size: 11px; + color: var(--at-label-tertiary); + display: inline-flex; + align-items: center; + gap: 6px; + flex: none; +} +/* \u63CF\u8FF0 12px/18px pre-wrap margin 5px 0\uFF1B\u4E24\u884C\u622A\u65AD */ +.task p { + font-size: 12px; + line-height: 18px; + color: var(--at-label-secondary); + white-space: pre-wrap; + margin: 5px 0; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} +.task p.expanded { -webkit-line-clamp: unset; display: block; } +/* \u5C55\u5F00\u5F00\u5173\uFF1Afloat right\uFF1B11px/20px\uFF1Bchevron 12px \u65CB\u8F6C 180\xB0 transition .12s */ +.expand-toggle { + float: right; + font-size: 11px; + line-height: 20px; + color: var(--at-label-tertiary); + background: none; + border: none; + cursor: pointer; + padding: 0; + margin-left: 10px; + font-family: inherit; + display: inline-flex; + align-items: center; + gap: 2px; +} +.expand-toggle:hover, .expand-toggle:focus-visible { color: var(--at-label-primary); } +.expand-toggle svg { transition: transform 0.12s; } +.expand-toggle.open svg { transform: rotate(180deg); } +.expand-toggle[hidden] { display: none; } +/* meta \u884C\uFF1A11px/20px\uFF1B\u5B50\u9879\u95F4\u8DDD 10px\uFF1Bwarning \u63D0\u9192\u8272\uFF08advisory \u975E\u9519\u8BEF\uFF09 */ +.task .meta { font-size: 11px; line-height: 20px; color: var(--at-label-tertiary); } +.task .meta > span { margin-right: 10px; } +.task .meta .warning { color: var(--at-warning-text); } +/* T5.7 \u6210\u5458\u4F1A\u8BDD\u67E5\u770B\u89C6\u56FE\uFF08V16\uFF1A\u65E0 DSH \u53C2\u7167\uFF0C\u5BBF\u4E3B\u98CE\u683C\uFF1B\u5224\u636E=\u4E0D\u7834\u7248+\u51E0\u4F55\u4E00\u81F4\uFF09 */ +.detail-view { display: flex; flex-direction: column; min-height: 0; flex: auto; } +.detail-head { + display: flex; + align-items: center; + gap: 8px; + padding: 4px 9px 8px 6px; + border-bottom: 0.5px solid var(--at-border-l2); + flex: none; +} +.detail-back { + display: inline-flex; + align-items: center; + gap: 4px; + background: none; + border: none; + color: var(--at-label-tertiary); + font: inherit; + font-size: 12px; + cursor: pointer; + padding: 2px 6px; + border-radius: 6px; +} +.detail-back:hover, .detail-back:focus-visible { color: var(--at-label-primary); background: color-mix(in srgb, var(--at-label-tertiary) 10%, transparent); } +.detail-title { font-size: 13px; font-weight: 500; color: var(--at-label-primary); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.detail-actions { margin-left: auto; display: inline-flex; gap: 6px; flex: none; } +.detail-action { + background: none; + border: 0.5px solid var(--at-border-l2); + border-radius: 6px; + color: var(--at-label-secondary); + font: inherit; + font-size: 11px; + line-height: 18px; + padding: 1px 8px; + cursor: pointer; +} +.detail-action:hover, .detail-action:focus-visible { color: var(--at-label-primary); border-color: var(--at-border-l3); } +.detail-list { overflow-y: auto; scrollbar-gutter: stable; padding: 8px 9px 16px 14px; flex: auto; min-height: 0; scrollbar-color: var(--at-scrollbar-thumb) transparent; } +.detail-state { font-size: 12px; color: var(--at-label-tertiary); padding: 16px 4px; display: flex; align-items: center; gap: 6px; } +.detail-state.error { color: var(--at-error-text); } +.msg { margin: 0 0 10px; min-width: 0; } +.msg-head { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--at-label-tertiary); margin-bottom: 2px; } +.msg-role { font-weight: 500; color: var(--at-label-secondary); } +.msg-time { font-variant-numeric: tabular-nums; } +.msg-text { + font-size: 12px; + line-height: 18px; + color: var(--at-label-primary); + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; +} +.msg.user .msg-text { color: var(--at-label-secondary); } +.msg-badge { + display: inline-flex; + align-items: center; + gap: 4px; + font-size: 10px; + line-height: 15px; + padding: 0 4px; + border-radius: 4px; + background: color-mix(in srgb, var(--at-business) 16%, transparent); + color: var(--at-business); +} +.msg-badge.hook { background: color-mix(in srgb, var(--at-label-tertiary) 14%, transparent); color: var(--at-label-tertiary); } +.tool-row { display: block; width: 100%; text-align: left; background: none; border: none; border-top: 0.5px solid var(--at-border-l2); padding: 4px 0; margin-top: 4px; font: inherit; cursor: pointer; color: var(--at-label-tertiary); } +.tool-row:hover, .tool-row:focus-visible { color: var(--at-label-primary); } +.tool-static { display: block; border-top: 0.5px solid var(--at-border-l2); padding: 4px 0; margin-top: 4px; color: var(--at-label-tertiary); } +.tool-row .tool-summary, .tool-static .tool-summary { display: inline-flex; align-items: center; gap: 6px; font-size: 11px; line-height: 20px; } +.tool-row .tool-name, .tool-static .tool-name { font-weight: 500; color: var(--at-label-secondary); } +.tool-row svg { transition: transform 0.12s; } +.tool-row.open svg { transform: rotate(180deg); } +.tool-detail { + display: none; + font-size: 11px; + line-height: 16px; + color: var(--at-label-tertiary); + white-space: pre-wrap; + word-break: break-word; + overflow-wrap: anywhere; + max-height: 200px; + overflow-y: auto; + margin: 2px 0 0 18px; +} +.tool-row.open + .tool-detail { display: block; } +/* toolGroup\uFF1A\u6309\u8F6E\u52A8\u4F5C\u7EC4\uFF08\u5934\u90E8\u4E00\u884C\u6C47\u603B\uFF1B\u5C55\u5F00\u9010\u6761\u5DE5\u5177\u884C\uFF0C\u7F29\u8FDB\u5BF9\u9F50 tool-detail\uFF09 */ +.tool-group-head { + display: flex; + align-items: center; + gap: 6px; + width: 100%; + text-align: left; + background: none; + border: none; + border-top: 0.5px solid var(--at-border-l2); + padding: 4px 0; + margin-top: 4px; + font: inherit; + color: var(--at-label-tertiary); + cursor: pointer; +} +.tool-group-head:hover, .tool-group-head:focus-visible { color: var(--at-label-primary); } +.tool-group-head .tool-group-label { font-size: 11px; line-height: 20px; color: var(--at-label-secondary); } +.tool-group-head:hover .tool-group-label, +.tool-group-head:focus-visible .tool-group-label { color: var(--at-label-primary); } +.tool-group-head svg { flex: none; transition: transform 0.12s; } +.tool-group.open .tool-group-head svg { transform: rotate(180deg); } +.tool-group-items { display: none; margin-left: 18px; } +.tool-group.open .tool-group-items { display: block; } +.tool-group-items > :first-child { border-top: none; } +.detail-pager { display: flex; align-items: center; gap: 8px; padding: 4px 0 8px; } +.detail-pager .detail-action[disabled] { opacity: 0.45; cursor: default; } +`; + var PANEL_CSS = ` +html, body { margin: 0; padding: 0; height: 100%; } +body { background: transparent; } +.at-root { height: 100%; display: flex; align-items: flex-start; justify-content: center; padding: 16px 0; } +.team-panel { margin: 0 auto; } +/* \u4F5C\u8005\u6837\u5F0F\u8868\u4E2D\u7684 display \u58F0\u660E\u4F1A\u8986\u76D6 UA \u7684 [hidden]{display:none}\uFF08\u5982 .detail-view \u7684 + display:flex\uFF09\uFF1A\u5217\u8868\u2194\u8BE6\u60C5\u5207\u6362\u5FC5\u987B\u7531 hidden \u771F\u6B63\u9690\u85CF\uFF0C\u5426\u5219\u8FD4\u56DE\u5217\u8868\u540E\u8BE6\u60C5\u6B8B\u7559\u5728\u4E0B\u65B9\u3002 */ +.team-panel [hidden] { display: none !important; } +`; + + // src/ui-core/dict.ts + var DICT = { + zh: { + trigger: "\u667A\u80FD\u4F53\u56E2\u961F", + loading: "\u6B63\u5728\u52A0\u8F7D\u56E2\u961F\u2026", + unavailable: "Team \u6682\u4E0D\u53EF\u7528", + failure: "\u56E2\u961F\u6301\u4E45\u8BB0\u5F55\u65E0\u6548\uFF1A{message}", + empty: "\u6682\u65E0\u5171\u4EAB\u4EFB\u52A1\uFF0C\u53EF\u4EE5\u901A\u8FC7\u5BF9\u8BDD\u521B\u5EFA", + roster: "\u6210\u5458", + tasks: "\u5171\u4EAB\u4EFB\u52A1", + model: "\u6A21\u578B", + open: "\u6253\u5F00\u6210\u5458\u4F1A\u8BDD", + current: "\u5F53\u524D\u4F1A\u8BDD", + owner: "Owner", + unowned: "\u672A\u5206\u914D", + blockedBy: "\u4F9D\u8D56", + writeScopes: "\u5199\u5165\u8303\u56F4", + ready: "\u53EF\u5F00\u59CB", + blocked: "\u88AB\u4F9D\u8D56\u963B\u585E", + "task.expand": "\u5C55\u5F00", + "task.collapse": "\u6536\u8D77", + "memberStatus.running": "\u8FD0\u884C\u4E2D", + "memberStatus.inactive": "\u672A\u8FD0\u884C", + "memberStatus.provisioning": "\u51C6\u5907\u4E2D", + "memberStatus.failed": "\u5931\u8D25", + "status.pending": "\u5F85\u5904\u7406", + "status.in_progress": "\u8FDB\u884C\u4E2D", + "status.completed": "\u5DF2\u5B8C\u6210" + }, + en: { + trigger: "Agent Team", + loading: "Loading Team\u2026", + unavailable: "Team is unavailable", + failure: "Invalid persisted Team record: {message}", + empty: "No shared tasks yet. Create them through the conversation.", + roster: "Members", + tasks: "Shared tasks", + model: "Model", + open: "Open member conversation", + current: "Current chat", + owner: "Owner", + unowned: "Unowned", + blockedBy: "Blocked by", + writeScopes: "Write scopes", + ready: "Ready", + blocked: "Blocked by dependencies", + "task.expand": "Show more", + "task.collapse": "Show less", + "memberStatus.running": "Running", + "memberStatus.inactive": "Inactive", + "memberStatus.provisioning": "Provisioning", + "memberStatus.failed": "Failed", + "status.pending": "Pending", + "status.in_progress": "In progress", + "status.completed": "Completed" + } + }; + var DETAIL_DICT = { + zh: { + "detail.back": "\u8FD4\u56DE", + "detail.title": "\u6210\u5458\u4F1A\u8BDD", + "detail.loading": "\u6B63\u5728\u52A0\u8F7D\u4F1A\u8BDD\u2026", + "detail.empty": "\u8BE5\u6210\u5458\u6682\u65E0\u4F1A\u8BDD\u6D88\u606F", + "detail.failed": "\u4F1A\u8BDD\u8BFB\u53D6\u5931\u8D25\uFF1A{message}", + "detail.refresh": "\u5237\u65B0", + "detail.copySessionId": "\u590D\u5236\u4F1A\u8BDD id", + "detail.copied": "\u5DF2\u590D\u5236", + "detail.earlier": "\u66F4\u65E9\u6D88\u606F", + "detail.wake": "\u8BF7\u6C42 Lead \u5524\u9192\u8BE5\u6210\u5458", + "detail.wakeInjected": "\u5DF2\u6CE8\u5165\u4E0B\u4E00\u8F6E\uFF1A\u8BF7\u6C42\u5524\u9192 {name}", + "detail.framedFrom": "Team \u6D88\u606F \xB7 \u6765\u81EA {name}", + "detail.hookBadge": "hook \u6CE8\u5165", + "detail.toolCall": "\u5DE5\u5177\u8C03\u7528", + "detail.noSession": "\u4F1A\u8BDD id \u672A\u843D\u5B9A\uFF08\u6210\u5458\u53EF\u80FD\u5C1A\u5728\u51C6\u5907\u4E2D\uFF09", + "detail.you": "\u6211", + "detail.count": "{n} \u6761", + "detail.toolGroup": "{n} \u4E2A\u52A8\u4F5C \xB7 {list}", + "detail.countSummary": "{n} \u6761 \xB7 \u5171 {sourceTotal} \u6761\u8F6C\u5F55" + }, + en: { + "detail.back": "Back", + "detail.title": "Member conversation", + "detail.loading": "Loading conversation\u2026", + "detail.empty": "No conversation messages for this member yet", + "detail.failed": "Conversation read failed: {message}", + "detail.refresh": "Refresh", + "detail.copySessionId": "Copy session id", + "detail.copied": "Copied", + "detail.earlier": "Earlier messages", + "detail.wake": "Ask Lead to wake this member", + "detail.wakeInjected": "Injected for next turn: wake request for {name}", + "detail.framedFrom": "Team message \xB7 from {name}", + "detail.hookBadge": "hook injected", + "detail.toolCall": "Tool call", + "detail.noSession": "Session id not settled yet (member may still be provisioning)", + "detail.you": "me", + "detail.count": "{n} items", + "detail.toolGroup": "{n} actions \xB7 {list}", + "detail.countSummary": "{n} items \xB7 of {sourceTotal} transcript items" + } + }; + function t(lang2, key, vars) { + return interpolate(DICT[lang2][key], vars); + } + function td(lang2, key, vars) { + return interpolate(DETAIL_DICT[lang2][key], vars); + } + function interpolate(template, vars) { + if (vars === void 0) return template; + return template.replace( + /\{(\w+)\}/g, + (m, k2) => k2 in vars ? String(vars[k2]) : m + ); + } + function langOfLocale(locale) { + return typeof locale === "string" && locale.toLowerCase().startsWith("zh") ? "zh" : "en"; + } + function statusKey(status) { + return status === "deleted" ? "status.completed" : `status.${status}`; + } + function memberStatusKey(status) { + return `memberStatus.${status}`; + } + + // src/ui-core/icons.ts + var svg = (inner, size) => ``; + function iconUser(size = 14) { + return svg('', size); + } + function iconChevron(size = 12) { + return svg('', size); + } + function iconArrowLeft(size = 14) { + return svg('', size); + } + + // src/ui-core/escape.ts + function esc2(s) { + return s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); + } + + // src/ui-core/render.ts + function isCompact(frame2) { + return frame2.members.length === 1 && frame2.tasks.length === 0; + } + function currentMemberId(frame2) { + const sid = frame2.meta.sessionId; + if (sid === void 0) return void 0; + return frame2.members.find((m) => m.sessionId === sid)?.id; + } + function isMemberDisabled(m, currentId) { + return m.id === currentId || m.status === "failed" || m.status === "provisioning"; + } + function memberDot(status) { + switch (status) { + case "running": + case "provisioning": + return "ongoing"; + case "failed": + return "error"; + case "inactive": + default: + return "icon"; + } + } + function taskDot(task) { + switch (task.status) { + case "in_progress": + return "ongoing"; + case "completed": + return "done"; + case "deleted": + return "idle"; + // 上游 deleted→idle(视图通常不含墓碑,防御口径) + case "pending": + default: + return task.ready ? "idle" : "warning"; + } + } + function dot(state) { + return ``; + } + function memberIndicator(m) { + const d2 = memberDot(m.status); + const inner = d2 === "icon" ? `${iconUser(14)}` : dot(d2); + return `${inner}`; + } + function renderMember(m, opts) { + const { lang: lang2, isCurrent, disabled } = opts; + const highlight = opts.highlightCurrent ?? isCurrent; + const cls = ["member", highlight ? "current" : ""].filter(Boolean).join(" "); + const nameRow = `${esc2(m.target)}` + (isCurrent ? `${esc2(t(lang2, "current"))}` : "") + ``; + const modelSuffix = m.model !== void 0 ? ` \xB7 ${esc2(t(lang2, "model"))}: ${esc2(m.model)}` : ""; + const sub = `${esc2(t(lang2, memberStatusKey(m.status)))}${modelSuffix}`; + const diag = m.diagnostics.length > 0 ? `${esc2(m.diagnostics[0])}` : ""; + const openAttr = disabled ? "" : ` title="${esc2(t(lang2, "open"))}"`; + return ``; + } + function renderRoster(frame2, lang2) { + const members = frame2.members; + const currentId = currentMemberId(frame2); + const countHtml = members.length > 1 ? `${members.length}` : ""; + const cards = members.map( + (m) => renderMember(m, { + lang: lang2, + // Tag 恒随当前会话;高亮/描边才受 members>1 限制(上游 TeamAction 同口径)。 + isCurrent: m.id === currentId, + highlightCurrent: m.id === currentId && members.length > 1, + disabled: isMemberDisabled(m, currentId) + }) + ).join(""); + return `

${esc2(t(lang2, "roster"))}${countHtml}

${cards}
`; + } + function renderTaskMeta(task, lang2, leadingHtml = "") { + const spans = []; + spans.push(`${esc2(task.id)}`); + const owner = task.ownerName !== void 0 ? esc2(task.ownerName) : esc2(t(lang2, "unowned")); + spans.push(`${esc2(t(lang2, "owner"))}: ${owner}`); + if (task.status === "pending") { + spans.push(`${esc2(t(lang2, task.ready ? "ready" : "blocked"))}`); + } + if (task.blockedBy.length > 0) { + spans.push(`${esc2(t(lang2, "blockedBy"))}: ${task.blockedBy.map(esc2).join(", ")}`); + } + if (task.writeScopes.length > 0) { + spans.push(`${esc2(t(lang2, "writeScopes"))}: ${task.writeScopes.map(esc2).join(", ")}`); + } + for (const w2 of task.writeScopeWarnings) { + spans.push(`${esc2(w2)}`); + } + return `
${leadingHtml}${spans.join("")}
`; + } + function renderTask(task, lang2) { + const state = `${dot(taskDot(task))}${esc2(t(lang2, statusKey(task.status)))}`; + const titleRow = `
${esc2(task.subject)}${state}
`; + const toggle = ``; + const desc = `

${esc2(task.description)}

`; + return `
` + titleRow + desc + renderTaskMeta(task, lang2, toggle) + `
`; + } + function renderTasks(frame2, lang2) { + if (frame2.tasks.length === 0) { + return `

${esc2(t(lang2, "empty"))}

`; + } + const cards = frame2.tasks.map((task) => renderTask(task, lang2)).join(""); + return `

${esc2(t(lang2, "tasks"))}${frame2.tasks.length}

${cards}
`; + } + function renderNotices(opts) { + const { lang: lang2 } = opts; + const out = []; + if (opts.navError !== void 0) { + out.push(``); + } + if (opts.loading === true) { + out.push(`
${dot("ongoing")}${esc2(t(lang2, "loading"))}
`); + } else if (opts.noTeam === true) { + out.push(`
${dot("warning")}${esc2(t(lang2, "unavailable"))}
`); + } + if (opts.failure !== void 0) { + out.push(``); + } + return out.join(""); + } + function renderPanelBody(frame2, lang2, runtime) { + const noTeam = frame2.team === null; + const notices = renderNotices({ + lang: lang2, + ...runtime?.navError !== void 0 ? { navError: runtime.navError } : {}, + ...runtime?.loading !== void 0 ? { loading: runtime.loading } : {}, + noTeam, + ...frame2.team?.failure !== void 0 ? { failure: frame2.team.failure } : {} + }); + if (noTeam && runtime?.loading !== true) { + return notices; + } + return notices + renderRoster(frame2, lang2) + renderTasks(frame2, lang2); + } + + // src/ui-core/detail-render.ts + function aggregateToolNames(tools) { + const counts = /* @__PURE__ */ new Map(); + for (const tool of tools) counts.set(tool.name, (counts.get(tool.name) ?? 0) + 1); + return [...counts.entries()].sort((a, b2) => b2[1] - a[1] || (a[0] < b2[0] ? -1 : a[0] > b2[0] ? 1 : 0)).map(([name, n]) => `${name}\xD7${n}`).join(" \xB7 "); + } + function renderToolEntry(tool) { + const hasPayload = tool.text !== void 0 && tool.text.length > 0; + const summary = `${hasPayload ? iconChevron(12) : ""}${esc2(tool.name)}${esc2(tool.status)}`; + return hasPayload ? `
${esc2(tool.text)}
` : `${summary}`; + } + function renderDetailItem(item, lang2) { + const time3 = item.ts.slice(11, 19); + const badge = item.framed !== void 0 ? `${esc2(td(lang2, "detail.framedFrom", { name: item.framed.from }))}` : ""; + if (item.kind === "toolCall") { + const tool = item.tool ?? { name: "?", status: "?" }; + const entry = { + ts: item.ts, + name: tool.name, + status: tool.status, + ...item.text !== void 0 ? { text: item.text } : {} + }; + return `
assistant${time3}
` + renderToolEntry(entry) + `
`; + } + if (item.kind === "toolGroup") { + const tools = item.tools ?? []; + const count = item.count ?? tools.length; + const label = td(lang2, "detail.toolGroup", { n: count, list: aggregateToolNames(tools) }); + return `
assistant${time3}
${tools.map((tool) => renderToolEntry(tool)).join("")}
`; + } + const roleLabel = item.role === "user" ? esc2(td(lang2, "detail.you")) : item.role; + return `
${roleLabel}${time3}${badge}
${esc2(item.text ?? "")}
`; + } + function renderDetailBody(st, lang2) { + if (st.kind === "loading") { + return `
${esc2(td(lang2, "detail.loading"))}
`; + } + if (st.kind === "error") { + const text = st.reason === "session-not-settled" ? td(lang2, "detail.noSession") : td(lang2, "detail.failed", { message: st.message }); + return `
${esc2(text)}
`; + } + const d2 = st.detail; + const count = `${esc2(td(lang2, "detail.countSummary", { n: d2.total, sourceTotal: d2.sourceTotal }))}`; + if (d2.page.items.length === 0) { + return `
${esc2(td(lang2, "detail.empty"))}
`; + } + const pager = d2.page.nextCursor !== void 0 ? `
${count}
` : `
${count}
`; + return pager + d2.page.items.map((item) => renderDetailItem(item, lang2)).join(""); + } + function renderDetailView(st, lang2, opts = {}) { + if (st.kind === "closed") return ""; + const actions = []; + if (st.kind === "ready") { + actions.push(``); + actions.push( + `` + ); + if (opts.wake === true) { + actions.push(``); + } + } + return `
${esc2(st.name)}${actions.join("")}
${renderDetailBody(st, lang2)}
`; + } + + // src/ui-core/expand.ts + function memoryExpandStore(initial) { + const set2 = new Set(initial ?? []); + return { + isExpanded: (id) => set2.has(id), + setExpanded: (id, v2) => { + if (v2) set2.add(id); + else set2.delete(id); + } + }; + } + function attachExpandBehavior(root2, store, labels) { + const observers = []; + const measure = (task) => { + const desc = task.querySelector("[data-task-desc]"); + const toggle = task.querySelector("[data-task-toggle]"); + if (desc === null || toggle === null) return; + const id = task.dataset.taskId ?? ""; + const expanded = store.isExpanded(id); + const overflow = desc.scrollHeight > desc.clientHeight + 1; + toggle.hidden = !(overflow || expanded); + const label = toggle.querySelector(".expand-label"); + if (label !== null) label.textContent = expanded ? labels.collapse : labels.expand; + toggle.setAttribute("aria-expanded", expanded ? "true" : "false"); + toggle.classList.toggle("open", expanded); + desc.classList.toggle("expanded", expanded); + }; + const tasks = () => Array.from(root2.querySelectorAll("article.task")); + for (const task of tasks()) { + const desc = task.querySelector("[data-task-desc]"); + if (desc !== null && typeof ResizeObserver !== "undefined") { + const ro = new ResizeObserver(() => measure(task)); + ro.observe(desc); + observers.push(ro); + } + measure(task); + } + const onClick = (ev) => { + const target = ev.target; + const toggle = target?.closest("[data-task-toggle]"); + if (toggle === null || toggle === void 0) return; + const task = toggle.closest("article.task"); + if (task === null) return; + const id = task.dataset.taskId ?? ""; + store.setExpanded(id, !store.isExpanded(id)); + measure(task); + }; + root2.addEventListener("click", onClick); + return () => { + root2.removeEventListener("click", onClick); + for (const ro of observers) ro.disconnect(); + }; + } + + // src/ui-core/request-sequencer.ts + var RequestSequencer = class { + #seq = 0; + begin() { + this.#seq += 1; + return this.#seq; + } + isCurrent(seq) { + return seq === this.#seq; + } + invalidate() { + this.#seq += 1; + } + }; + + // src/panel/main.ts + var VIEW_URI = "team://view"; + var HEARTBEAT_MS = 25e3; + var app = new i({ name: "agent-team-panel", version: "0.5.0" }, {}); + var frame = null; + var lang = "zh"; + var navError; + var detailState = { kind: "closed" }; + var expandStore = memoryExpandStore(); + var detachExpand = null; + var heartbeatTimer = null; + var heartbeatInFlight = false; + var viewSequencer = new RequestSequencer(); + var detailSequencer = new RequestSequencer(); + var style = document.createElement("style"); + style.textContent = COMPONENT_CSS + PANEL_CSS; + document.head.appendChild(style); + var root = document.createElement("div"); + root.className = "at-root"; + root.innerHTML = ``; + document.body.appendChild(root); + var panelEl = root.querySelector(".team-panel"); + var listView = root.querySelector("[data-list-view]"); + var detailView = root.querySelector("[data-detail-view]"); + function applyHostContext() { + const ctx = app.getHostContext(); + const theme = ctx?.theme === "dark" ? "dark" : "light"; + document.documentElement.dataset.theme = theme; + document.documentElement.style.colorScheme = theme; + const vars = ctx?.styles?.variables; + if (vars !== void 0) { + for (const [k2, v2] of Object.entries(vars)) { + if (typeof v2 === "string") document.documentElement.style.setProperty(k2, v2); + } + } + lang = langOfLocale(ctx?.locale); + panelEl.setAttribute("aria-label", DICT[lang].trigger); + document.documentElement.lang = lang === "zh" ? "zh-CN" : "en"; + } + function restoreWidgetState() { + const ws = app.getHostContext()?.["zcode/widgetState"]; + if (ws !== void 0 && Array.isArray(ws.expanded)) { + expandStore = memoryExpandStore(new Set(ws.expanded)); + } + } + var saveWidgetQueued = false; + function persistWidgetState() { + if (saveWidgetQueued) return; + saveWidgetQueued = true; + setTimeout(() => { + saveWidgetQueued = false; + const expanded = [...expandedIds()]; + void app.request({ method: "ui/set-widget-state", params: { widgetState: { expanded } } }, EmptyResultSchema).catch(() => void 0); + }, 200); + } + function expandedIds() { + const ids = /* @__PURE__ */ new Set(); + for (const el of root.querySelectorAll("article.task")) { + const toggle = el.querySelector("[data-task-toggle]"); + if (toggle !== null && toggle.getAttribute("aria-expanded") === "true") { + ids.add(el.dataset.taskId ?? ""); + } + } + return ids; + } + function parseToolText(res) { + const first = res.content?.[0]; + if (first === void 0 || first.type !== "text" || typeof first.text !== "string") { + throw new Error("empty tool result"); + } + return first.text; + } + async function readView() { + const seq = viewSequencer.begin(); + const res = await app.readServerResource({ uri: VIEW_URI }); + const first = res.contents?.[0]; + const text = first !== void 0 && "text" in first ? first.text : void 0; + if (text === void 0) throw new Error("empty view resource"); + const next = JSON.parse(text); + if (!viewSequencer.isCurrent(seq)) return; + frame = next; + navError = void 0; + render(); + } + async function refreshViaCall() { + const seq = viewSequencer.begin(); + const res = await app.callServerTool({ name: "team_panel_call", arguments: { action: "refresh" } }); + const body = JSON.parse(parseToolText(res)); + if (body.frame === void 0) throw new Error(body.error?.message ?? "refresh failed"); + if (!viewSequencer.isCurrent(seq)) return; + frame = body.frame; + navError = void 0; + render(); + } + async function subscribe() { + await app.request( + { method: "resources/subscribe", params: { uri: VIEW_URI } }, + EmptyResultSchema + ); + await readView(); + } + app.setNotificationHandler(ResourceUpdatedNotificationSchema, async (n) => { + if (n.params.uri !== VIEW_URI) return; + try { + await readView(); + } catch { + try { + await refreshViaCall(); + } catch (err) { + navError = err instanceof Error ? err.message : String(err); + render(); + } + } + }); + function startHeartbeat() { + if (heartbeatTimer !== null) return; + heartbeatTimer = setInterval(() => { + if (heartbeatInFlight) return; + heartbeatInFlight = true; + void (async () => { + try { + await app.callServerTool({ name: "team_panel_call", arguments: { label: "heartbeat" } }); + } catch { + try { + await subscribe(); + } catch { + try { + await refreshViaCall(); + } catch (err) { + navError = err instanceof Error ? err.message : String(err); + render(); + } + } + } finally { + heartbeatInFlight = false; + } + })(); + }, HEARTBEAT_MS); + } + async function openDetail(memberId, name, cursor) { + const seq = detailSequencer.begin(); + const fromList = detailState.kind === "closed"; + detailState = { kind: "loading", memberId, name }; + render(); + if (fromList) detailView.focus(); + try { + const res = await app.callServerTool({ + name: "team_panel_call", + arguments: { + action: "detail", + target: memberId, + ...cursor !== void 0 ? { cursor } : {} + } + }); + if (!detailSequencer.isCurrent(seq)) return; + const body = JSON.parse(parseToolText(res)); + if (body.detail !== void 0) { + detailState = { kind: "ready", memberId, name, detail: body.detail }; + } else { + detailState = { + kind: "error", + memberId, + name, + message: body.error?.message ?? "detail failed", + ...body.error?.reason !== void 0 ? { reason: body.error.reason } : {} + }; + } + } catch (err) { + if (!detailSequencer.isCurrent(seq)) return; + detailState = { kind: "error", memberId, name, message: err instanceof Error ? err.message : String(err) }; + } + render(); + } + function closeDetail() { + detailSequencer.invalidate(); + detailState = { kind: "closed" }; + render(); + } + function injectWake(name) { + void app.updateModelContext({ + content: [ + { + type: "text", + text: `[agent-team \u9762\u677F\u6CE8\u5165] \u7528\u6237\u5728\u300C\u667A\u80FD\u4F53\u56E2\u961F\u300D\u9762\u677F\u8BF7\u6C42\u5173\u6CE8\u6210\u5458 "${name}"\uFF1A\u8BF7\u67E5\u770B\u8BE5\u6210\u5458\u5F53\u524D\u72B6\u6001\uFF0C\u5FC5\u8981\u65F6\u7ECF send_message \u5524\u9192\u6216\u63A8\u8FDB\u5176\u4EFB\u52A1\u3002` + } + ] + }).then( + () => { + const btn = detailView.querySelector("[data-detail-wake]"); + if (btn !== null) btn.textContent = td(lang, "detail.wakeInjected", { name }); + }, + () => void 0 + // 注入失败不打断视图(下钻是提示性动作) + ); + } + function render() { + const inDetail = detailState.kind !== "closed"; + listView.hidden = inDetail; + detailView.hidden = !inDetail; + panelEl.classList.toggle("compact", frame !== null && isCompact(frame) && !inDetail); + if (inDetail) { + detailView.innerHTML = renderDetailView(detailState, lang, { wake: true }); + bindDetail(); + return; + } + if (detachExpand !== null) { + detachExpand(); + detachExpand = null; + } + if (frame === null) { + listView.innerHTML = renderPanelBody( + { type: "view", stateVersion: 4, team: null, members: [], tasks: [], meta: { generatedAt: "", revision: 0 } }, + lang, + { loading: true, ...navError !== void 0 ? { navError } : {} } + ); + return; + } + listView.innerHTML = renderPanelBody( + frame, + lang, + { + ...navError !== void 0 ? { navError } : {}, + loading: false + } + ); + detachExpand = attachExpandBehavior(listView, expandStore, { + expand: DICT[lang]["task.expand"], + collapse: DICT[lang]["task.collapse"] + }); + } + listView.addEventListener("click", (ev) => { + const target = ev.target; + if (target?.closest("[data-task-toggle]") !== null && target !== void 0) { + persistWidgetState(); + return; + } + const member = target?.closest("button.member"); + if (member === null || member === void 0 || member.disabled) return; + const id = member.dataset.memberId; + if (id === void 0) return; + void openDetail(id, member.querySelector(".name")?.textContent ?? id); + }); + function bindDetail() { + detailView.querySelector("[data-detail-back]")?.addEventListener("click", closeDetail); + const reload = () => { + if (detailState.kind === "ready" || detailState.kind === "error") { + void openDetail(detailState.memberId, detailState.name); + } + }; + detailView.querySelector("[data-detail-refresh]")?.addEventListener("click", reload); + detailView.querySelector("[data-detail-retry]")?.addEventListener("click", reload); + detailView.querySelector("[data-detail-wake]")?.addEventListener("click", () => { + if (detailState.kind === "ready") injectWake(detailState.name); + }); + detailView.querySelector("[data-detail-copy]")?.addEventListener("click", () => { + if (detailState.kind !== "ready") return; + const sid = detailState.detail.sessionId; + void navigator.clipboard?.writeText(sid).then(void 0, () => fallbackCopy(sid)); + const btn = detailView.querySelector("[data-detail-copy]"); + if (btn !== null) { + btn.textContent = td(lang, "detail.copied"); + setTimeout(() => { + if (btn.isConnected) btn.textContent = td(lang, "detail.copySessionId"); + }, 1500); + } + }); + detailView.querySelector("[data-detail-earlier]")?.addEventListener("click", (ev) => { + const cursor = Number(ev.currentTarget.dataset.cursor); + if (detailState.kind === "ready" && Number.isFinite(cursor)) { + void openDetail(detailState.memberId, detailState.name, cursor); + } + }); + for (const head of detailView.querySelectorAll("button.tool-group-head")) { + head.addEventListener("click", () => { + const group = head.closest(".tool-group"); + const open = group?.classList.toggle("open") ?? false; + head.setAttribute("aria-expanded", open ? "true" : "false"); + }); + } + for (const row of detailView.querySelectorAll("button.tool-row")) { + row.addEventListener("click", () => { + const open = row.classList.toggle("open"); + row.setAttribute("aria-expanded", open ? "true" : "false"); + }); + } + } + function fallbackCopy(text) { + const ta = document.createElement("textarea"); + ta.value = text; + ta.style.position = "fixed"; + ta.style.opacity = "0"; + document.body.appendChild(ta); + ta.select(); + try { + document.execCommand("copy"); + } catch { + } + ta.remove(); + } + app.onhostcontextchanged = () => { + applyHostContext(); + render(); + }; + void (async () => { + applyHostContext(); + restoreWidgetState(); + render(); + try { + await app.connect(); + applyHostContext(); + restoreWidgetState(); + try { + await subscribe(); + } catch { + } + try { + await refreshViaCall(); + } catch (err) { + if (frame === null) { + try { + await readView(); + } catch (readErr) { + navError = readErr instanceof Error ? readErr.message : err instanceof Error ? err.message : String(err); + render(); + } + } + } + } catch (err) { + navError = err instanceof Error ? err.message : String(err); + render(); + } + startHeartbeat(); + })(); +})(); diff --git a/external_plugins/agent-team/runtime/ui/team-companion.html b/external_plugins/agent-team/runtime/ui/team-companion.html new file mode 100644 index 00000000..59c4c5b7 --- /dev/null +++ b/external_plugins/agent-team/runtime/ui/team-companion.html @@ -0,0 +1,1105 @@ + + + + + +Agent Team · Companion + + + + + \ No newline at end of file diff --git a/external_plugins/agent-team/runtime/ui/team-panel.html b/external_plugins/agent-team/runtime/ui/team-panel.html new file mode 100644 index 00000000..716b358a --- /dev/null +++ b/external_plugins/agent-team/runtime/ui/team-panel.html @@ -0,0 +1,16061 @@ + + + + + +Agent Team + + + + + \ No newline at end of file diff --git a/external_plugins/agent-team/skills/team-coordination/SKILL.md b/external_plugins/agent-team/skills/team-coordination/SKILL.md new file mode 100644 index 00000000..022b5393 --- /dev/null +++ b/external_plugins/agent-team/skills/team-coordination/SKILL.md @@ -0,0 +1,49 @@ +--- +name: team-coordination +description: 智能体团队协作策略(agent-team 插件辅通道)。当目标可通过多代理并行/委派受益时主动使用:编排团队成员、创建或管理 teammate 成员、成员间消息、共享任务板/任务认领、任务验收与团队并行开发。 +--- + +# 智能体团队 · 协调策略(stage-3 定版;〔对齐轮修订 2026-10-17〕换版 0.2.1-alpha.5) + +本 skill 是团队策略的**辅通道**(主通道 = SessionStart hook additionalContext;兜底 = 工具 description)。三层文本同源:`src/mcp/policy.ts`(teamPolicy/POLICY_TEXT,冻结包 06 §3.1 逐字全文 + D7 冻结替换句;首段门控句随 0.2.1 删除,D5)。〔stage-6.5 D26,2026-10-24;issue #9 三档化 D28,2026-11-02〕teamPolicy 四段已按 2026-11-04 的消息交付与任务闭环修订;另有 **Lead-only 模式段**(off/auto/always 三档,见下节,主通道按 `leadMode` 与建队状态插值)。 + +## 策略全文(与 hook 主通道同文;以下为 `interrupt=true` 默认版) + +> `interrupt:false` 时 hook 主通道的第 4 段插值为 `for send_message, or as owner...`,且 +> `interrupt_agent` 不注册。本 skill 是静态 Markdown,无法运行时插值;以 hook 注入为准。 + +Agent Teams is available in this session + +The Team Lead and all teammates share the same working directory and filesystem. Edits are immediately visible to every member. Split write work into disjoint scopes, record expected write scopes on shared tasks, and use task dependencies when work must be ordered. Write-scope overlap is advisory, not a lock. + +Prefer read/edit/write for file changes. If a file operation reports that the file changed since you last read it, read the current file again, rebase your intended change onto the new content, and retry. Bash, formatters, code generators, and scripts are not fully protected by the filesystem version guard; coordinate them explicitly and have the Lead review the final diff and run tests. + +Use the target returned by spawn_teammate or list_agents for send_message and interrupt_agent, or as owner when assigning or filtering shared tasks. send_message queues delivery to a running teammate's next turn boundary and starts or resumes an inactive teammate. The Lead receives queued messages through wait_agent during its current turn, with session hooks as a fallback. inactive means no turn is executing; it does not describe task completion, success, failure, or waiting for other agents. provisioning means member creation is in progress; failed means member creation failed. A peer message starts with its sender name. A successful send does not mean the recipient has processed it. Each delegated unit needs a shared task with acceptance criteria. Create it before dispatching the work; the teammate must list/get it, claim with the current revision, perform the work, then complete and report to the Lead. An initial prompt or an output file is not a task-board record. Task readiness never starts an owner. Use wait_agent to receive pending Lead inbox messages before sending follow-ups, even when teammates are inactive. With no pending messages, it waits for new changes and returns noProgress immediately when no other member can produce a change; it never wakes a member. Consume returned messages, then recheck shared tasks before deciding whether more work or another message is needed. Re-list after wakeup or timeout. The Lead must wait for required teammates before giving the final answer. + +## Lead 模式三档(〔stage-6.5 D26;issue #9 三档化 D28〕2026-11-02 定稿) + +userConfig `leadMode` 三档(**新默认 `auto`**;旧值 `orchestrator`/`collaborator` 统一按 `auto` 处理,激进编排需显式改 `always`): + +- **`off`**:完全关闭——hook 不注入任何团队上下文(策略/身份/收件箱均停),daemon 不注册团队工具(tools/list 为 0 个,直连调用被拒)。 +- **`auto`**(默认,按需委派):该会话**未建过队**时注入 = 策略 + 身份(无模式段,对齐上游按需组队语义);**曾建过队**(`teams//members/` 存在非 sessionId 的成员目录——failed 也算,持久判定不回退)时,于身份段后追加以下英文段(逐字 = `src/mcp/policy.ts` 的 `ON_DEMAND_SECTION_TEXT`): + +> Lead operating mode (on-demand): Judge each request by delegation value before using the team. Handle work directly yourself — with a one-line reason, no forced tasks — for questions and explanations, small changes confined to a single file, read-only research summaries, or when every teammate is busy and the request is unrelated to existing work. Use the team workflow when work clearly benefits from multiple roles in parallel, when write scopes must be split across members, when a long task deserves its own context, or when the user explicitly names members. When you delegate, turn each delegated unit into a shared task whose description states concrete acceptance criteria, assign an owner, record expected write scopes, and set dependencies when ordering matters. Require each owner to self-check and report changed files and test results before completing. When a task reaches completed, verify it independently: review the final diff and run the relevant tests yourself; if it fails, reopen the task with concrete findings; if it passes, append your acceptance verdict to the task description — a task is done when completed plus your recorded acceptance. Reuse idle teammates before spawning new ones and keep one member per role, within the member limit. Wait for required teammates and synthesize their results for the final answer. + + 首次建队发生在会话中途时(SessionStart 已过),首成员 `spawn_teammate` 的成功结果尾部会附完整按需协作规范(`FIRST_SPAWN_NOTE`,独立 text 块,不改结果 JSON)。 +- **`always`**:始终主动编排——Lead 会话于身份段后追加以下英文段(逐字 = `src/mcp/policy.ts` 的 `ORCHESTRATOR_SECTION_TEXT`,即原 D26 编排段): + +> Lead operating mode (orchestrator): Decompose any non-trivial multi-step request into disjoint work packages before doing hands-on work. Do not edit files or implement directly except trivial one-line fixes or when no eligible member exists — delegate by creating teammates that cover the roles the goal requires. You decide the team composition and spawn it without being asked; consult the user only when the choice materially changes cost or scope. Turn every delegated unit into a shared task whose description states concrete acceptance criteria, assign an owner, record expected write scopes, and set dependencies when ordering matters. Require each owner to self-check and report changed files and test results before completing. When a task reaches completed, verify it independently: review the final diff and run the relevant tests yourself; if it fails, reopen the task with concrete findings; if it passes, append your acceptance verdict to the task description — a task is done when completed plus your recorded acceptance. Reuse idle teammates before spawning new ones and keep one member per role, within the member limit. You still wait for required teammates and synthesize their results for the final answer. + +- 本 skill 是静态 Markdown,无法运行时插值;teammate 会话恒不注入任何模式段。以 hook 注入为准。 +- 验收协议(D27):owner `complete` = 提交;Lead 必须独立复核(读 diff + 跑测试 + 核验任务描述中的 + 验收标准);失败 → `reopen` 附具体问题(completed→pending+去 owner);通过 → `edit` 在 description + 追加验收记录(面板可见),构成「标记完成」闭环。 + +## ZCode 场景说明 + +1. **团队工具**(server `team-daemon`):默认 9 个——`spawn_teammate` / `send_message` / `list_agents` / `interrupt_agent` / `wait_agent` / `team_task_create` / `team_task_list` / `team_task_get` / `team_task_update`;配置 `interrupt:false` 时为 8 个(不注册 `interrupt_agent`,策略中也不会出现该工具指引)。Lead-only 三操作(spawn / interrupt / reassign)在执行层强制;非成员会话调用一律 `TEAM_NOT_MEMBER`。〔issue #9 D28〕另有 userConfig `leadMode`(`auto` 默认 / `always` / `off`):`off` = **0 个团队工具**(不注册、直连调用被拒);`auto`/`always` = 9/8 工具(只影响 Lead 会话注入哪段模式文本)。 +2. **建队友用 `spawn_teammate`**,不要用内置 Task/Agent 工具建一次性子代理(teammate 会话启动参数含 `--disallowed-tools Task` 遮蔽,D6)。 +3. **消息投递**(〔对齐轮〕0.2.1 口径):`send_message` 成功 = 收件接受(工具结果 `{"sent":true}`);不保证接收方已处理;ZCode 无 steer → 运行中目标在回合边界交付(D2 适配),成功即免重发。目标离线导致确定性失败时,工具会返回可读错误,不要当作已送达。 +4. **任务板 CAS**:先 `team_task_get`/`team_task_list` 读最新 `revision`,再 `team_task_update(action, expected_revision)`;收到 `TEAM_TASK_STALE_REVISION` → 重新 get 后重试。 +5. **错误自恢复**:工具失败结果 = `{"error":{"code","message"}}` 紧凑 JSON;code 是 27 个 TEAM_* 错误码之一(〔对齐轮〕0.2.1 删 TEAM_MAILBOX_FULL),按 message 指引重试或改参。 +6. **等待与交付**:用 `wait_agent` 读取 Lead 的待收消息,成员已 inactive 也应先收消息;返回的 `messages` 包含发送者与原文。先处理结果、核对任务板,再决定是否需要后续消息;空收件箱且无可推进成员才返回 noProgress。委派单元先建共享任务,成员先 get/claim 再执行、complete、向 Lead 交付,Lead 独立验收并记录。 diff --git a/marketplace.json b/marketplace.json index c7f09a06..d8d8f64f 100644 --- a/marketplace.json +++ b/marketplace.json @@ -1443,6 +1443,35 @@ "mcp", "verification" ] + }, + { + "name": "agent-team", + "displayName": "智能体团队", + "displayName_i18n": { + "en": "Agent Teams", + "zh-CN": "智能体团队" + }, + "source": "./external_plugins/agent-team", + "description": "智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。", + "description_i18n": { + "en": "Agent Teams: spawn and coordinate teammate sessions with a shared task board and member messaging.", + "zh-CN": "智能体团队:在会话中创建并协调多个 teammate 子会话、共享任务板与成员消息。" + }, + "version": "0.5.5-rc.1", + "author": { + "name": "Vincent Zuo", + "url": "https://github.com/Vincent-chk" + }, + "category": "developer-tools", + "icon": "https://cdn-zcode.z.ai/zcode/official-plugin/assets/agent-team/icon.png", + "keywords": [ + "agent-teams", + "multi-agent", + "teammates", + "task-board", + "orchestration", + "mcp-apps" + ] } ] } \ No newline at end of file