agestra 4.3.1 → 4.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agestra",
3
- "version": "4.3.1",
3
+ "version": "4.3.2",
4
4
  "description": "Claude Code plugin — orchestrate Ollama, Gemini, and Codex for multi-AI debates, cross-validation, and GraphRAG memory",
5
5
  "mcpServers": {
6
6
  "agestra": {
package/README.ko.md CHANGED
@@ -123,7 +123,7 @@ Turborepo 모노레포, 8개 패키지:
123
123
  | `ai_analyze_files` | 파일을 디스크에서 읽어 공급자에게 질문과 함께 전송 |
124
124
  | `ai_compare` | 같은 프롬프트를 여러 공급자에 보내 응답 비교 |
125
125
 
126
- ### 에이전트 오케스트레이션 (20개)
126
+ ### 에이전트 오케스트레이션 (11개)
127
127
 
128
128
  | 도구 | 설명 |
129
129
  |------|------|
@@ -134,19 +134,10 @@ Turborepo 모노레포, 8개 패키지:
134
134
  | `agent_debate_conclude` | 토론 종료 및 최종 트랜스크립트 생성 |
135
135
  | `agent_debate_moderate` | 완전 자동화 토론 — 세션 생성, Specialist 에이전트 참여 라운드 실행, 합의 검출, 요약만 반환 |
136
136
  | `agent_debate_review` | 문서를 여러 공급자에게 독립적으로 리뷰 요청 |
137
- | `agent_assign_task` | 특정 공급자에게 작업 위임 |
138
- | `agent_task_status` | 작업 완료 상태 및 결과 확인 |
139
- | `agent_dispatch` | 공급자 간 병렬 작업 분배 (의존성 순서 지원) |
140
137
  | `agent_cross_validate` | 출력 교차 검증 (에이전트 등급 검증자만 가능) |
141
- | `agent_task_chain_create` | 의존성과 체크포인트가 있는 다단계 작업 체인 생성 |
142
- | `agent_task_chain_step` | 체인의 다음 (또는 지정) 단계 실행 |
143
- | `agent_task_chain_step_async` | 단계를 비동기로 실행 (논블로킹) |
144
- | `agent_task_chain_await` | 비동기 단계 완료 대기 |
145
- | `agent_task_chain_status` | 체인 진행 상태 및 단계 결과 확인 |
146
138
  | `agent_changes_review` | 격리된 작업의 파일 변경 리뷰 |
147
139
  | `agent_changes_accept` | 격리된 작업의 변경 수락 및 병합 |
148
140
  | `agent_changes_reject` | 변경 거부 및 격리 워크트리 정리 |
149
- | `session_list` | 에이전트 세션 목록 조회 (유형/상태 필터링) |
150
141
 
151
142
  ### CLI 워커 (4개)
152
143
 
package/README.md CHANGED
@@ -123,7 +123,7 @@ Turborepo monorepo with 8 packages:
123
123
  | `ai_analyze_files` | Read files from disk and send contents with a question to a provider |
124
124
  | `ai_compare` | Send the same prompt to multiple providers, compare responses |
125
125
 
126
- ### Agent Orchestration (20)
126
+ ### Agent Orchestration (11)
127
127
 
128
128
  | Tool | Description |
129
129
  |------|-------------|
@@ -134,19 +134,10 @@ Turborepo monorepo with 8 packages:
134
134
  | `agent_debate_conclude` | End a debate and generate final transcript |
135
135
  | `agent_debate_moderate` | Run a fully automated debate — creates session, runs rounds with specialist agents, detects consensus, returns summary only |
136
136
  | `agent_debate_review` | Send a document to multiple providers for independent review |
137
- | `agent_assign_task` | Delegate a task to a specific provider |
138
- | `agent_task_status` | Check task completion and result |
139
- | `agent_dispatch` | Distribute tasks across providers in parallel (dependency ordering) |
140
137
  | `agent_cross_validate` | Cross-validate outputs (agent-tier validators only) |
141
- | `agent_task_chain_create` | Create a multi-step task chain with dependencies and checkpoints |
142
- | `agent_task_chain_step` | Execute the next (or specified) step in a chain |
143
- | `agent_task_chain_step_async` | Execute a step asynchronously (non-blocking) |
144
- | `agent_task_chain_await` | Wait for an async step to complete |
145
- | `agent_task_chain_status` | Check chain progress and step results |
146
138
  | `agent_changes_review` | Review file changes from an isolated task |
147
139
  | `agent_changes_accept` | Accept and merge changes from an isolated task |
148
140
  | `agent_changes_reject` | Reject changes and clean up the isolated worktree |
149
- | `session_list` | List all agent sessions with optional type/status filtering |
150
141
 
151
142
  ### CLI Workers (4)
152
143
 
@@ -193,7 +193,7 @@ Do NOT duplicate the reviewer's checklist. If you suspect code quality issues ou
193
193
  <Tool_Usage>
194
194
  - `agent_cross_validate` — request external AI cross-review of outputs
195
195
  - `agent_changes_review` — review file changes in isolated worktrees
196
- - `agent_dispatch` with `auto_qa: true` — AutoQA runs build/test automatically after dispatch
196
+ - `cli_worker_status` / `cli_worker_collect` — check CLI worker results for verification
197
197
  - `provider_list` — check available validators
198
198
  - `memory_search` — check for related prior findings
199
199
  - `memory_dead_ends` — check for known issues in this area
@@ -14,7 +14,7 @@ disallowedTools: Write, Edit, NotebookEdit
14
14
  ---
15
15
 
16
16
  <Role>
17
- You are a full-lifecycle orchestrator for multi-AI work. You do NOT write code. Your job is to clarify requirements, decompose tasks, assign them to the right AI providers or agents, supervise parallel execution, inspect results, and enforce consistency. You are the single point of coordination — every task goes through you.
17
+ You are a full-lifecycle orchestrator for multi-AI work using a hybrid architecture. You coordinate Claude workers through the Team API (TeamCreate, TaskCreate, TaskUpdate, TaskList, TaskGet, SendMessage, Agent with team_name) and manage external AI providers through MCP tools (cli_worker_spawn, ai_chat, debates, etc.). You do NOT write code. Your job is to clarify requirements, decompose tasks, assign them to the right AI providers or workers, supervise parallel execution, inspect results, and enforce consistency. You are the single point of coordination — every task goes through you.
18
18
  </Role>
19
19
 
20
20
  <Execution_Mode>
@@ -47,22 +47,22 @@ If the request is already clear (specific files, functions, concrete criteria):
47
47
 
48
48
  Before executing, gather context:
49
49
 
50
- 1. Call `environment_check` to get the full capability map:
51
- - Which CLI tools are installed (codex, gemini, tmux)
52
- - Which Ollama models are available and their tier classifications
53
- - Whether autonomous work is possible (CLI workers + git worktree)
54
- - Available modes: claude_only, independent, debate, team
55
- 2. Call `provider_list` for provider availability.
56
- 3. Call `trace_summary` to get provider quality scores and difficulty qualifications.
57
- - Review each provider's overall average quality score
58
- - Note which difficulty levels each provider qualifies for (low/medium/high)
59
- - Providers with no quality data are treated as new (low difficulty only)
60
- 4. Read existing design documents in `docs/plans/`.
61
- 5. Store environment capabilities for later mode selection:
62
- - `can_autonomous_work`: CLI workers available?
63
- - `available_providers`: which are online?
64
- - `ollama_tiers`: model size classifications
65
- 6. In autonomous mode: show the design document to the user but do NOT wait for approval.
50
+ 1. Call `environment_check` to get the full capability map:
51
+ - Which CLI tools are installed (codex, gemini, tmux)
52
+ - Which Ollama models are available and their tier classifications
53
+ - Whether autonomous work is possible (CLI workers + git worktree)
54
+ - Available modes: claude_only, independent, debate, team
55
+ 2. Call `provider_list` for provider availability.
56
+ 3. Call `trace_summary` to get provider quality scores and difficulty qualifications.
57
+ - Review each provider's overall average quality score
58
+ - Note which difficulty levels each provider qualifies for (low/medium/high)
59
+ - Providers with no quality data are treated as new (low difficulty only)
60
+ 4. Read existing design documents in `docs/plans/`.
61
+ 5. Store environment capabilities for later mode selection:
62
+ - `can_autonomous_work`: CLI workers available?
63
+ - `available_providers`: which are online?
64
+ - `ollama_tiers`: model size classifications
65
+ 6. In autonomous mode: show the design document to the user but do NOT wait for approval.
66
66
 
67
67
  ### Phase 2: Task Design
68
68
 
@@ -74,8 +74,8 @@ Decompose the work into independent, assignable tasks:
74
74
 
75
75
  | Option | Description |
76
76
  |--------|-------------|
77
- | **Claude only** | Claude handles all work using project/global agents |
78
- | **Multi-AI** | CLI AIs work autonomously, Ollama handles simple tasks, Claude supervises as lead |
77
+ | **Claude only** | Claude handles all work via Team API workers |
78
+ | **Multi-AI** | CLI AIs work autonomously, Ollama handles simple tasks, Claude workers handle core tasks |
79
79
 
80
80
  If no external providers available: skip selection, proceed with Claude only.
81
81
  In autonomous mode: auto-select based on task complexity:
@@ -91,47 +91,57 @@ Decompose the work into independent, assignable tasks:
91
91
  3. **Task Routing** — Route each task by AI suitability:
92
92
 
93
93
  If **"Claude only"** selected:
94
- - **Architecture/design** `agestra-designer` agent
95
- - **Code review** `agestra-reviewer` agent
96
- - **Quality verification** `agestra-qa` agent
97
- - **Implementation**Claude directly or project-specific agents
94
+ - ALL tasks are routed through the Team API
95
+ - Create a team via `TeamCreate`, define tasks via `TaskCreate`, spawn Claude workers via `Agent(team_name=...)`
96
+ - Role assignment within the team:
97
+ - Architecture/design tasks worker with designer role
98
+ - Code review tasks → worker with reviewer role
99
+ - Quality verification → worker with QA role
100
+ - Implementation → workers with implementer role
98
101
 
99
102
  If **"Multi-AI"** selected:
100
103
 
101
104
  | Task Characteristics | Route To |
102
105
  |---------------------|----------|
103
- | Complex implementation, multi-step reasoning | Codex/Gemini CLI worker (`cli_worker_spawn`) |
104
- | Simple transforms, formatting, pattern application | Ollama (`ai_chat`, tier-matched model) |
105
- | Core design decisions | Claude directly |
106
- | Test writing | Claude agent (tester) |
107
- | Code review | Claude agent (reviewer) |
108
-
109
- **Quality-Based Provider Selection:**
110
-
111
- Before assigning any task, determine its difficulty level:
112
- - **low**: Simple chat, basic formatting, straightforward review
113
- - **medium**: Design discussion, code generation, analysis, debate turns
114
- - **high**: Complex architecture, cross-validation, multi-component refactoring
115
-
116
- Then filter providers by qualification:
117
- 1. Check `trace_summary` output for each provider's difficulty qualification
118
- 2. Only assign a task to a provider that qualifies for its difficulty level
119
- 3. Among qualified providers, prefer the one with the highest task-specific quality score
120
- 4. If no provider qualifies, fall back to Claude for the task
121
- 5. New providers (no quality data) start at low difficulty — assign simple tasks first to build their track record
122
-
123
- 4. Define dependency relationships between tasks.
106
+ | Complex implementation, multi-step reasoning | MCP: `cli_worker_spawn` (Codex/Gemini) |
107
+ | Simple transforms, formatting, pattern application | MCP: `ai_chat` (Ollama, tier-matched model) |
108
+ | Core implementation, design decisions | Team API: Claude workers |
109
+ | Test writing, review | Team API: Claude workers |
110
+
111
+ **Quality-Based Provider Selection:**
112
+
113
+ Before assigning any task, determine its difficulty level:
114
+ - **low**: Simple chat, basic formatting, straightforward review
115
+ - **medium**: Design discussion, code generation, analysis, debate turns
116
+ - **high**: Complex architecture, cross-validation, multi-component refactoring
117
+
118
+ Then filter providers by qualification:
119
+ 1. Check `trace_summary` output for each provider's difficulty qualification
120
+ 2. Only assign a task to a provider that qualifies for its difficulty level
121
+ 3. Among qualified providers, prefer the one with the highest task-specific quality score
122
+ 4. If no provider qualifies, fall back to a Claude worker for the task
123
+ 5. New providers (no quality data) start at low difficulty — assign simple tasks first to build their track record
124
+
125
+ 4. Define dependency relationships between tasks.
124
126
 
125
127
  5. Present the distribution plan to the user and wait for approval before executing (supervised mode).
126
128
 
127
129
  ### Phase 3: Parallel Execution
128
130
 
129
- Execute approved tasks:
131
+ Execute approved tasks across both coordination systems in parallel:
130
132
 
131
- **Claude tasks:**
132
- - Direct implementation or agent spawn (existing behavior).
133
+ **Claude tasks (Team API):**
134
+ 1. `TeamCreate(name="impl-{feature}", maxWorkers=N)` create a worker team sized to the task count.
135
+ 2. `TaskCreate` x M — define each task with subject and structured description containing:
136
+ - Objective: what to accomplish
137
+ - Scope: file paths to read and modify
138
+ - Constraints: what NOT to do
139
+ - Acceptance criteria: what "done" looks like
140
+ 3. `Agent(team_name="impl-{feature}", prompt=<Worker_Preamble> + role)` x N — spawn Claude workers into the team, each with the standard Worker Preamble and their assigned role.
141
+ 4. Monitor via `TaskList` — poll task statuses periodically. Coordinate via `SendMessage` when workers need guidance or cross-worker information.
142
+ 5. On all tasks completed: `SendMessage(to="all", type="shutdown")` — signal workers to stop.
133
143
 
134
- **CLI Worker tasks** (when "Multi-AI"):
144
+ **CLI Worker tasks (MCP, parallel with above):**
135
145
  1. For each CLI worker task, call `cli_worker_spawn` with:
136
146
  - `provider`: codex or gemini
137
147
  - `task_description`: detailed task prompt (see Prompt Crafting)
@@ -142,50 +152,42 @@ Execute approved tasks:
142
152
  - `success_criteria`: verification commands
143
153
  - `use_worktree`: true (git isolation)
144
154
  - `timeout_minutes`: based on task complexity
145
-
146
- 2. Independent tasks run concurrently (parallel Agent calls in one message).
147
- 3. Dependent tasks run sequentially wait for blockers to complete.
148
-
149
- **Ollama tasks** (when "Multi-AI"):
155
+ 2. Monitor: call `cli_worker_status` every 30 seconds for each active worker.
156
+ 3. On worker COMPLETED: call `cli_worker_collect`, review the diff.
157
+ 4. On worker FAILED: log the error, decide:
158
+ - If transient failure (crash, timeout) and retry_count < 1 → worker auto-retries.
159
+ - Otherwise re-route to a different provider or a Claude worker via Team API.
160
+ 5. On worker TIMEOUT: worker transitions to FAILED, follow failure handling above.
161
+
162
+ **Ollama tasks (MCP):**
150
163
  - Call `ai_chat` with tier-matched model for simple tasks.
151
- - Claude applies the Ollama-generated changes.
152
-
153
- **Monitor Loop** (active while CLI workers are running):
154
- - Every 30 seconds: call `cli_worker_status` for each active worker.
155
- - On worker COMPLETED: call `cli_worker_collect`, review the diff.
156
- - On worker FAILED: log the error, decide:
157
- - If transient failure (crash, timeout) and retry_count < 1 → worker auto-retries.
158
- - Otherwise → re-route to a different provider or Claude.
159
- - On worker TIMEOUT: worker transitions to FAILED, follow failure handling above.
160
- - Continue monitor loop until all workers have reached a terminal state (COMPLETED, FAILED, CANCELLED).
161
-
162
- **Worker result integration:**
163
- - Review git diff from each completed worktree.
164
- - Check for file overlap between workers:
165
- - No overlap → sequential merge (safe).
166
- - Overlap detected → check if changes are non-conflicting (different line ranges).
167
- - True conflict → spawn `agestra-moderator` to propose resolution, or resolve manually.
168
- - Merge clean results: `git merge --no-ff` each worker branch.
164
+ - Pass the result to a Claude worker via `SendMessage` for application to the codebase.
165
+
166
+ **Result Integration:**
167
+ - Claude workers: changes are already applied on the main branch (no merge needed).
168
+ - CLI workers: call `agent_changes_review` to see full diff, then `agent_changes_accept` or `agent_changes_reject`.
169
+ - File overlap between tracks: detect conflicts between Claude worker changes and CLI worker worktrees. If overlap found, use `agestra-moderator` to propose resolution or resolve manually before merging CLI worker results.
169
170
 
170
171
  ### Phase 4: Result Inspection
171
172
 
172
173
  After each task completes:
173
174
 
174
175
  1. Review the output from each AI.
175
- 2. For isolated tasks, call `agent_changes_review` to see full diff of file changes.
176
- 3. Compare changes against the design document:
176
+ 2. For CLI worker tasks: call `agent_changes_review` to see full diff of worktree changes.
177
+ 3. For Claude worker tasks: use `Read`, `Glob`, `Grep` to verify the changes applied to the codebase.
178
+ 4. Compare changes against the design document:
177
179
  - Missing items → re-instruct the AI with specific guidance
178
180
  - Extra items not in design → flag to user
179
181
  - Modifications that deviate from design → reject and re-instruct
180
- 4. Check cross-AI consistency:
182
+ 5. Check cross-AI consistency:
181
183
  - Interface contracts match between components
182
184
  - Naming conventions are consistent
183
185
  - No conflicting changes to shared files
184
186
  - Import/export chains are complete
185
- 5. If issues found → craft a detailed correction prompt and re-assign to the same AI.
186
- 6. If all checks pass:
187
- - For isolated tasks, call `agent_changes_accept` to merge changes
188
- - For rejected tasks, call `agent_changes_reject` with reason
187
+ 6. If issues found → craft a detailed correction prompt and re-assign to the same AI (or a Claude worker via `SendMessage`).
188
+ 7. If all checks pass:
189
+ - For CLI worker tasks: call `agent_changes_accept` to merge worktree changes
190
+ - For rejected CLI worker tasks: call `agent_changes_reject` with reason
189
191
  - Proceed to Phase 5 (QA Cycle).
190
192
 
191
193
  ### Phase 5: QA Cycle
@@ -237,7 +239,9 @@ Provide a clear summary to the user:
237
239
  - What was requested
238
240
  - Execution mode used (supervised/autonomous)
239
241
  - Work mode used (Claude only / Multi-AI)
240
- - How tasks were distributed (which AI did what)
242
+ - Team API details: team name, worker count, task distribution
243
+ - How tasks were distributed (which AI/worker did what)
244
+ - Task completion summary: total tasks, completed, failed, re-routed
241
245
  - What changed (files modified, features added)
242
246
  - QA cycle: how many cycles ran, what was auto-fixed
243
247
  - Quality Gate: TRUST 5 results
@@ -245,6 +249,46 @@ Provide a clear summary to the user:
245
249
 
246
250
  </Workflow>
247
251
 
252
+ <Worker_Preamble>
253
+ Standard instructions for all Claude workers spawned via Agent(team_name=...):
254
+
255
+ ## Worker Protocol
256
+
257
+ You are a team worker in team "{team_name}".
258
+ Assigned role: {role_description}
259
+
260
+ ### Workflow
261
+ 1. Claim work: TaskList → find matching task → TaskUpdate(taskId, status="in_progress")
262
+ 2. Execute: Read task description, follow file scope, respect constraints, implement per acceptance criteria
263
+ 3. Report completion: TaskUpdate(taskId, status="completed") with summary → SendMessage(to="lead")
264
+ 4. Handle failures: SendMessage(to="lead") if blocked, TaskUpdate(status="failed") if failed
265
+ 5. Continue or stop: Check TaskList for more, stop on shutdown message
266
+
267
+ ### Rules
268
+ - Only modify files in task scope
269
+ - Follow existing code conventions
270
+ - No extras beyond task scope
271
+ - Message lead for cross-worker coordination
272
+ - Do not commit or push
273
+ </Worker_Preamble>
274
+
275
+ <Stage_Handoff>
276
+ When transitioning between workflow phases, create a handoff document summarizing:
277
+
278
+ Phase 2→3 Handoff:
279
+ - Work mode selected (Claude only / Multi-AI)
280
+ - Total tasks, Claude workers count, CLI workers count
281
+ - Task dependency graph
282
+ - Risk flags (shared files, complex tasks)
283
+ - Context for workers (design doc path, naming conventions, key decisions)
284
+
285
+ Phase 3→4 Handoff:
286
+ - Execution results per task (who did what, status)
287
+ - File overlap detection results
288
+ - Pending merges (CLI worktrees)
289
+ - Flags for inspector
290
+ </Stage_Handoff>
291
+
248
292
  <Prompt_Crafting>
249
293
  When assigning tasks to external AIs, you MUST write detailed prompts. A vague prompt produces vague results. Every prompt to an external AI must include:
250
294
 
@@ -297,35 +341,64 @@ The design document is the authority. If an AI's output conflicts with the desig
297
341
  </Principles>
298
342
 
299
343
  <Tool_Usage>
300
- - `environment_check` — full capability map at start (CLI tools, Ollama tiers, available modes)
301
- - `provider_list` check available providers
302
- - `provider_health` — verify a specific provider's status
303
- - `trace_summary` — provider quality scores, difficulty qualifications, and performance stats
304
- - `ollama_models` — assess model capabilities for routing
305
- - `cli_worker_spawn` — spawn CLI AI in autonomous mode (worktree + preflight security)
306
- - `cli_worker_status` — check worker progress (FSM state, heartbeat, output tail)
307
- - `cli_worker_collect` — collect completed worker results (git diff, output, exit code)
308
- - `cli_worker_stop` — stop a running worker (SIGTERM SIGKILL + worktree cleanup)
309
- - `agent_assign_task` — assign work to a specific provider (use `isolate: true` for git worktree isolation)
310
- - `agent_dispatch` — parallel task distribution with dependencies (use `auto_qa: true` for automatic QA)
311
- - `ai_compare` — get multiple perspectives on the same question
344
+
345
+ ## Team API (Claude Worker Coordination)
346
+ - `TeamCreate` — create a worker team with max worker count
347
+ - `TaskCreate` — define a task with subject and description for workers to claim
348
+ - `TaskUpdate` — update task status (workers use this to claim/complete/fail)
349
+ - `TaskList` — list all tasks and their status
350
+ - `TaskGet` — get details of a specific task
351
+ - `SendMessage` — DM a worker, broadcast to all, or send shutdown signal
352
+ - `Agent(team_name=...)` — spawn a Claude worker into the team
353
+
354
+ ## MCP (External AI & Infrastructure)
355
+ - `environment_check` — detect CLI tools, Ollama models, infrastructure
356
+ - `provider_list` / `provider_health` — check external AI availability
357
+ - `trace_summary` / `trace_record` / `trace_compare` — provider quality tracking
358
+ - `ai_chat` / `ai_analyze_files` / `ai_compare` — query external AI
359
+ - `agent_debate_create/turn/status/summary/list/close/reset` — multi-AI debates
312
360
  - `agent_cross_validate` — cross-validate outputs between providers
313
- - `agent_task_chain_create` create multi-step task chains with dependency ordering and checkpoints
314
- - `agent_task_chain_step` execute next step in a chain (pauses at checkpoints for your review)
315
- - `agent_task_chain_status` check chain progress and step outputs
316
- - `agent_changes_review` — review file changes from isolated worktree (full diff)
317
- - `agent_changes_accept` merge worktree changes to main branch
318
- - `agent_changes_reject` — discard worktree changes
319
- - `memory_search` — check for prior work on similar tasks
320
- - `memory_dead_ends` — avoid previously failed approaches
361
+ - `cli_worker_spawn` / `cli_worker_status` / `cli_worker_collect` / `cli_worker_stop` manage Codex/Gemini CLI workers
362
+ - `agent_changes_review` / `agent_changes_accept` / `agent_changes_reject` review/merge worktree changes
363
+ - `memory_search` / `memory_store` / `memory_query` / `memory_graph_status` / `memory_connections` / `memory_dead_ends` — knowledge graph
364
+ - `workspace_review_*`code review documents
365
+ - `ollama_models` / `ollama_pull` Ollama model management
366
+
321
367
  </Tool_Usage>
322
368
 
369
+ <MCP_Tool_Communication>
370
+
371
+ Before calling any MCP tool (prefixed with `plugin:agestra:agestra`), output a **one-line summary** in the user's language explaining what you are about to do and why.
372
+
373
+ MCP tool calls display raw parameter JSON to the user, which is hard to read. A brief summary beforehand gives the user context.
374
+
375
+ **Rules:**
376
+ - Before calling an MCP tool, output a one-line summary in the user's language
377
+ - When calling multiple MCP tools in sequence, summarize the overall flow first
378
+ - Simple status checks (status, list) may skip the summary
379
+
380
+ **Example:**
381
+
382
+ Bad (no summary):
383
+ ```
384
+ [calls cli_worker_spawn]
385
+ ```
386
+
387
+ Good (summary first):
388
+ ```
389
+ Spawning a Codex CLI worker to refactor the auth module in an isolated worktree.
390
+ [calls cli_worker_spawn]
391
+ ```
392
+
393
+ </MCP_Tool_Communication>
394
+
323
395
  <Constraints>
324
396
  - Do NOT write, edit, or create files. Delegate all implementation.
325
397
  - Do NOT skip the user approval step before executing tasks (in supervised mode).
326
398
  - Do NOT assign complex tasks to small Ollama models.
327
399
  - Do NOT accept "simplified" or "partial" results from AIs.
328
400
  - Do NOT proceed to QA until you've inspected all results yourself.
401
+ - Do NOT use MCP tools for Claude worker management — use Team API instead.
329
402
  - If no external providers are available, inform the user and suggest Claude-only execution with appropriate agents (designer, reviewer).
330
403
  - Communicate in the user's language.
331
404
  </Constraints>
package/dist/bundle.js CHANGED
@@ -10,7 +10,7 @@ var za=Object.create;var BW=Object.defineProperty;var ia=Object.getOwnPropertyDe
10
10
  deps: ${l}}`};var v1={keyword:"dependencies",type:"object",schemaType:"object",error:wG.error,code(G){let[I,l]=J1(G);gF(G,I),AF(G,l)}};function J1({schema:G}){let I={},l={};for(let b in G){if(b==="__proto__")continue;let Z=Array.isArray(G[b])?I:l;Z[b]=G[b]}return[I,l]}function gF(G,I=G.schema){let{gen:l,data:b,it:Z}=G;if(Object.keys(I).length===0)return;let c=l.let("missing");for(let W in I){let d=I[W];if(d.length===0)continue;let N=(0,AZ.propertyInData)(l,b,W,Z.opts.ownProperties);G.setParams({property:W,depsCount:d.length,deps:d.join(", ")}),Z.allErrors?l.if(N,()=>{for(let Y of d)(0,AZ.checkReportMissingProp)(G,Y)}):(l.if((0,BY._)`${N} && (${(0,AZ.checkMissingProp)(G,d,c)})`),(0,AZ.reportMissingProp)(G,c),l.else())}}wG.validatePropertyDeps=gF;function AF(G,I=G.schema){let{gen:l,data:b,keyword:Z,it:c}=G,W=l.name("valid");for(let d in I)(0,w1.alwaysValidSchema)(c,I[d])||(l.if((0,AZ.propertyInData)(l,b,d,c.opts.ownProperties),()=>{let N=G.subschema({keyword:Z,schemaProp:d},W);G.mergeValidEvaluated(N,W)},()=>l.var(W,!0)),G.ok(W))}wG.validateSchemaDeps=AF;wG.default=v1});var oF=J(rY=>{"use strict";Object.defineProperty(rY,"__esModule",{value:!0});var kF=B(),E1=q(),y1={message:"property name must be valid",params:({params:G})=>(0,kF._)`{propertyName: ${G.propertyName}}`},s1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:y1,code(G){let{gen:I,schema:l,data:b,it:Z}=G;if((0,E1.alwaysValidSchema)(Z,l))return;let c=I.name("valid");I.forIn("key",b,W=>{G.setParams({propertyName:W}),G.subschema({keyword:"propertyNames",data:W,dataTypes:["string"],propertyName:W,compositeRule:!0},c),I.if((0,kF.not)(c),()=>{G.error(!0),Z.allErrors||I.break()})}),G.ok(c)}};rY.default=s1});var MY=J(OY=>{"use strict";Object.defineProperty(OY,"__esModule",{value:!0});var EW=lG(),mG=B(),t1=oG(),yW=q(),C1={message:"must NOT have additional properties",params:({params:G})=>(0,mG._)`{additionalProperty: ${G.additionalProperty}}`},e1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:C1,code(G){let{gen:I,schema:l,parentSchema:b,data:Z,errsCount:c,it:W}=G;if(!c)throw new Error("ajv implementation error");let{allErrors:d,opts:N}=W;if(W.props=!0,N.removeAdditional!=="all"&&(0,yW.alwaysValidSchema)(W,l))return;let Y=(0,EW.allSchemaProperties)(b.properties),m=(0,EW.allSchemaProperties)(b.patternProperties);V(),G.ok((0,mG._)`${c} === ${t1.default.errors}`);function V(){I.forIn("key",Z,H=>{!Y.length&&!m.length?X(H):I.if(h(H),()=>X(H))})}function h(H){let n;if(Y.length>8){let u=(0,yW.schemaRefOrVal)(W,b.properties,"properties");n=(0,EW.isOwnProperty)(I,u,H)}else Y.length?n=(0,mG.or)(...Y.map(u=>(0,mG._)`${H} === ${u}`)):n=mG.nil;return m.length&&(n=(0,mG.or)(n,...m.map(u=>(0,mG._)`${(0,EW.usePattern)(G,u)}.test(${H})`))),(0,mG.not)(n)}function R(H){I.code((0,mG._)`delete ${Z}[${H}]`)}function X(H){if(N.removeAdditional==="all"||N.removeAdditional&&l===!1){R(H);return}if(l===!1){G.setParams({additionalProperty:H}),G.error(),d||I.break();return}if(typeof l=="object"&&!(0,yW.alwaysValidSchema)(W,l)){let n=I.name("valid");N.removeAdditional==="failing"?(F(H,n,!1),I.if((0,mG.not)(n),()=>{G.reset(),R(H)})):(F(H,n),d||I.if((0,mG.not)(n),()=>I.break()))}}function F(H,n,u){let p={keyword:"additionalProperties",dataProp:H,dataPropType:yW.Type.Str};u===!1&&Object.assign(p,{compositeRule:!0,createErrors:!1,allErrors:!1}),G.subschema(p,n)}}};OY.default=e1});var xF=J(KY=>{"use strict";Object.defineProperty(KY,"__esModule",{value:!0});var g1=HZ(),zF=lG(),jY=q(),iF=MY(),A1={keyword:"properties",type:"object",schemaType:"object",code(G){let{gen:I,schema:l,parentSchema:b,data:Z,it:c}=G;c.opts.removeAdditional==="all"&&b.additionalProperties===void 0&&iF.default.code(new g1.KeywordCxt(c,iF.default,"additionalProperties"));let W=(0,zF.allSchemaProperties)(l);for(let V of W)c.definedProperties.add(V);c.opts.unevaluated&&W.length&&c.props!==!0&&(c.props=jY.mergeEvaluated.props(I,(0,jY.toHash)(W),c.props));let d=W.filter(V=>!(0,jY.alwaysValidSchema)(c,l[V]));if(d.length===0)return;let N=I.name("valid");for(let V of d)Y(V)?m(V):(I.if((0,zF.propertyInData)(I,Z,V,c.opts.ownProperties)),m(V),c.allErrors||I.else().var(N,!0),I.endIf()),G.it.definedProperties.add(V),G.ok(N);function Y(V){return c.opts.useDefaults&&!c.compositeRule&&l[V].default!==void 0}function m(V){G.subschema({keyword:"properties",schemaProp:V,dataProp:V},N)}}};KY.default=A1});var OF=J(DY=>{"use strict";Object.defineProperty(DY,"__esModule",{value:!0});var UF=lG(),sW=B(),BF=q(),rF=q(),L1={keyword:"patternProperties",type:"object",schemaType:"object",code(G){let{gen:I,schema:l,data:b,parentSchema:Z,it:c}=G,{opts:W}=c,d=(0,UF.allSchemaProperties)(l),N=d.filter(F=>(0,BF.alwaysValidSchema)(c,l[F]));if(d.length===0||N.length===d.length&&(!c.opts.unevaluated||c.props===!0))return;let Y=W.strictSchema&&!W.allowMatchingProperties&&Z.properties,m=I.name("valid");c.props!==!0&&!(c.props instanceof sW.Name)&&(c.props=(0,rF.evaluatedPropsToName)(I,c.props));let{props:V}=c;h();function h(){for(let F of d)Y&&R(F),c.allErrors?X(F):(I.var(m,!0),X(F),I.if(m))}function R(F){for(let H in Y)new RegExp(F).test(H)&&(0,BF.checkStrictMode)(c,`property ${H} matches pattern ${F} (use allowMatchingProperties)`)}function X(F){I.forIn("key",b,H=>{I.if((0,sW._)`${(0,UF.usePattern)(G,F)}.test(${H})`,()=>{let n=N.includes(F);n||G.subschema({keyword:"patternProperties",schemaProp:F,dataProp:H,dataPropType:rF.Type.Str},m),c.opts.unevaluated&&V!==!0?I.assign((0,sW._)`${V}[${H}]`,!0):!n&&!c.allErrors&&I.if((0,sW.not)(m),()=>I.break())})})}}};DY.default=L1});var MF=J(SY=>{"use strict";Object.defineProperty(SY,"__esModule",{value:!0});var k1=q(),o1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(G){let{gen:I,schema:l,it:b}=G;if((0,k1.alwaysValidSchema)(b,l)){G.fail();return}let Z=I.name("valid");G.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Z),G.failResult(Z,()=>G.reset(),()=>G.error())},error:{message:"must NOT be valid"}};SY.default=o1});var jF=J(TY=>{"use strict";Object.defineProperty(TY,"__esModule",{value:!0});var z1=lG(),i1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:z1.validateUnion,error:{message:"must match a schema in anyOf"}};TY.default=i1});var KF=J(qY=>{"use strict";Object.defineProperty(qY,"__esModule",{value:!0});var tW=B(),x1=q(),U1={message:"must match exactly one schema in oneOf",params:({params:G})=>(0,tW._)`{passingSchemas: ${G.passing}}`},B1={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:U1,code(G){let{gen:I,schema:l,parentSchema:b,it:Z}=G;if(!Array.isArray(l))throw new Error("ajv implementation error");if(Z.opts.discriminator&&b.discriminator)return;let c=l,W=I.let("valid",!1),d=I.let("passing",null),N=I.name("_valid");G.setParams({passing:d}),I.block(Y),G.result(W,()=>G.reset(),()=>G.error(!0));function Y(){c.forEach((m,V)=>{let h;(0,x1.alwaysValidSchema)(Z,m)?I.var(N,!0):h=G.subschema({keyword:"oneOf",schemaProp:V,compositeRule:!0},N),V>0&&I.if((0,tW._)`${N} && ${W}`).assign(W,!1).assign(d,(0,tW._)`[${d}, ${V}]`).else(),I.if(N,()=>{I.assign(W,!0),I.assign(d,V),h&&G.mergeEvaluated(h,tW.Name)})})}}};qY.default=B1});var DF=J(fY=>{"use strict";Object.defineProperty(fY,"__esModule",{value:!0});var r1=q(),O1={keyword:"allOf",schemaType:"array",code(G){let{gen:I,schema:l,it:b}=G;if(!Array.isArray(l))throw new Error("ajv implementation error");let Z=I.name("valid");l.forEach((c,W)=>{if((0,r1.alwaysValidSchema)(b,c))return;let d=G.subschema({keyword:"allOf",schemaProp:W},Z);G.ok(Z),G.mergeEvaluated(d)})}};fY.default=O1});var qF=J(PY=>{"use strict";Object.defineProperty(PY,"__esModule",{value:!0});var CW=B(),TF=q(),M1={message:({params:G})=>(0,CW.str)`must match "${G.ifClause}" schema`,params:({params:G})=>(0,CW._)`{failingKeyword: ${G.ifClause}}`},j1={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:M1,code(G){let{gen:I,parentSchema:l,it:b}=G;l.then===void 0&&l.else===void 0&&(0,TF.checkStrictMode)(b,'"if" without "then" and "else" is ignored');let Z=SF(b,"then"),c=SF(b,"else");if(!Z&&!c)return;let W=I.let("valid",!0),d=I.name("_valid");if(N(),G.reset(),Z&&c){let m=I.let("ifClause");G.setParams({ifClause:m}),I.if(d,Y("then",m),Y("else",m))}else Z?I.if(d,Y("then")):I.if((0,CW.not)(d),Y("else"));G.pass(W,()=>G.error(!0));function N(){let m=G.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},d);G.mergeEvaluated(m)}function Y(m,V){return()=>{let h=G.subschema({keyword:m},d);I.assign(W,d),G.mergeValidEvaluated(h,W),V?I.assign(V,(0,CW._)`${m}`):G.setParams({ifClause:m})}}}};function SF(G,I){let l=G.schema[I];return l!==void 0&&!(0,TF.alwaysValidSchema)(G,l)}PY.default=j1});var fF=J(_Y=>{"use strict";Object.defineProperty(_Y,"__esModule",{value:!0});var K1=q(),D1={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:G,parentSchema:I,it:l}){I.if===void 0&&(0,K1.checkStrictMode)(l,`"${G}" without "if" is ignored`)}};_Y.default=D1});var PF=J($Y=>{"use strict";Object.defineProperty($Y,"__esModule",{value:!0});var S1=oY(),T1=sF(),q1=zY(),f1=CF(),P1=eF(),_1=LF(),$1=oF(),Iy=MY(),Gy=xF(),ly=OF(),by=MF(),Zy=jF(),cy=KF(),Wy=DF(),dy=qF(),Ny=fF();function Yy(G=!1){let I=[by.default,Zy.default,cy.default,Wy.default,dy.default,Ny.default,$1.default,Iy.default,_1.default,Gy.default,ly.default];return G?I.push(T1.default,f1.default):I.push(S1.default,q1.default),I.push(P1.default),I}$Y.default=Yy});var _F=J(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});var RI=B(),my={message:({schemaCode:G})=>(0,RI.str)`must match format "${G}"`,params:({schemaCode:G})=>(0,RI._)`{format: ${G}}`},Vy={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:my,code(G,I){let{gen:l,data:b,$data:Z,schema:c,schemaCode:W,it:d}=G,{opts:N,errSchemaPath:Y,schemaEnv:m,self:V}=d;if(!N.validateFormats)return;Z?h():R();function h(){let X=l.scopeValue("formats",{ref:V.formats,code:N.code.formats}),F=l.const("fDef",(0,RI._)`${X}[${W}]`),H=l.let("fType"),n=l.let("format");l.if((0,RI._)`typeof ${F} == "object" && !(${F} instanceof RegExp)`,()=>l.assign(H,(0,RI._)`${F}.type || "string"`).assign(n,(0,RI._)`${F}.validate`),()=>l.assign(H,(0,RI._)`"string"`).assign(n,F)),G.fail$data((0,RI.or)(u(),p()));function u(){return N.strictSchema===!1?RI.nil:(0,RI._)`${W} && !${n}`}function p(){let e=m.$async?(0,RI._)`(${F}.async ? await ${n}(${b}) : ${n}(${b}))`:(0,RI._)`${n}(${b})`,g=(0,RI._)`(typeof ${n} == "function" ? ${e} : ${n}.test(${b}))`;return(0,RI._)`${n} && ${n} !== true && ${H} === ${I} && !${g}`}}function R(){let X=V.formats[c];if(!X){u();return}if(X===!0)return;let[F,H,n]=p(X);F===I&&G.pass(e());function u(){if(N.strictSchema===!1){V.logger.warn(g());return}throw new Error(g());function g(){return`unknown format "${c}" ignored in schema at path "${Y}"`}}function p(g){let aI=g instanceof RegExp?(0,RI.regexpCode)(g):N.code.formats?(0,RI._)`${N.code.formats}${(0,RI.getProperty)(c)}`:void 0,DI=l.scopeValue("formats",{key:c,ref:g,code:aI});return typeof g=="object"&&!(g instanceof RegExp)?[g.type||"string",g.validate,(0,RI._)`${DI}.validate`]:["string",g,DI]}function e(){if(typeof X=="object"&&!(X instanceof RegExp)&&X.async){if(!m.$async)throw new Error("async format in sync schema");return(0,RI._)`await ${n}(${b})`}return typeof H=="function"?(0,RI._)`${n}(${b})`:(0,RI._)`${n}.test(${b})`}}}};Im.default=Vy});var $F=J(Gm=>{"use strict";Object.defineProperty(Gm,"__esModule",{value:!0});var hy=_F(),Ry=[hy.default];Gm.default=Ry});var Ia=J(hb=>{"use strict";Object.defineProperty(hb,"__esModule",{value:!0});hb.contentVocabulary=hb.metadataVocabulary=void 0;hb.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];hb.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var la=J(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});var Xy=YF(),Fy=vF(),ay=PF(),Qy=$F(),Ga=Ia(),Hy=[Xy.default,Fy.default,(0,ay.default)(),Qy.default,Ga.metadataVocabulary,Ga.contentVocabulary];lm.default=Hy});var Za=J(eW=>{"use strict";Object.defineProperty(eW,"__esModule",{value:!0});eW.DiscrError=void 0;var ba;(function(G){G.Tag="tag",G.Mapping="mapping"})(ba||(eW.DiscrError=ba={}))});var Wa=J(Zm=>{"use strict";Object.defineProperty(Zm,"__esModule",{value:!0});var Rb=B(),bm=Za(),ca=VW(),py=pZ(),uy=q(),ny={message:({params:{discrError:G,tagName:I}})=>G===bm.DiscrError.Tag?`tag "${I}" must be string`:`value of tag "${I}" must be in oneOf`,params:({params:{discrError:G,tag:I,tagName:l}})=>(0,Rb._)`{error: ${G}, tag: ${l}, tagValue: ${I}}`},wy={keyword:"discriminator",type:"object",schemaType:"object",error:ny,code(G){let{gen:I,data:l,schema:b,parentSchema:Z,it:c}=G,{oneOf:W}=Z;if(!c.opts.discriminator)throw new Error("discriminator: requires discriminator option");let d=b.propertyName;if(typeof d!="string")throw new Error("discriminator: requires propertyName");if(b.mapping)throw new Error("discriminator: mapping is not supported");if(!W)throw new Error("discriminator: requires oneOf keyword");let N=I.let("valid",!1),Y=I.const("tag",(0,Rb._)`${l}${(0,Rb.getProperty)(d)}`);I.if((0,Rb._)`typeof ${Y} == "string"`,()=>m(),()=>G.error(!1,{discrError:bm.DiscrError.Tag,tag:Y,tagName:d})),G.ok(N);function m(){let R=h();I.if(!1);for(let X in R)I.elseIf((0,Rb._)`${Y} === ${X}`),I.assign(N,V(R[X]));I.else(),G.error(!1,{discrError:bm.DiscrError.Mapping,tag:Y,tagName:d}),I.endIf()}function V(R){let X=I.name("valid"),F=G.subschema({keyword:"oneOf",schemaProp:R},X);return G.mergeEvaluated(F,Rb.Name),X}function h(){var R;let X={},F=n(Z),H=!0;for(let e=0;e<W.length;e++){let g=W[e];if(g?.$ref&&!(0,uy.schemaHasRulesButRef)(g,c.self.RULES)){let DI=g.$ref;if(g=ca.resolveRef.call(c.self,c.schemaEnv.root,c.baseId,DI),g instanceof ca.SchemaEnv&&(g=g.schema),g===void 0)throw new py.default(c.opts.uriResolver,c.baseId,DI)}let aI=(R=g?.properties)===null||R===void 0?void 0:R[d];if(typeof aI!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${d}"`);H=H&&(F||n(g)),u(aI,e)}if(!H)throw new Error(`discriminator: "${d}" must be required`);return X;function n({required:e}){return Array.isArray(e)&&e.includes(d)}function u(e,g){if(e.const)p(e.const,g);else if(e.enum)for(let aI of e.enum)p(aI,g);else throw new Error(`discriminator: "properties/${d}" must have "const" or "enum"`)}function p(e,g){if(typeof e!="string"||e in X)throw new Error(`discriminator: "${d}" values must be unique strings`);X[e]=g}}}};Zm.default=wy});var da=J((bk,vy)=>{vy.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:!0,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:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},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:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},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:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},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:!0}});var Wm=J((WI,cm)=>{"use strict";Object.defineProperty(WI,"__esModule",{value:!0});WI.MissingRefError=WI.ValidationError=WI.CodeGen=WI.Name=WI.nil=WI.stringify=WI.str=WI._=WI.KeywordCxt=WI.Ajv=void 0;var Jy=bF(),Ey=la(),yy=Wa(),Na=da(),sy=["/properties"],gW="http://json-schema.org/draft-07/schema",Xb=class extends Jy.default{_addVocabularies(){super._addVocabularies(),Ey.default.forEach(I=>this.addVocabulary(I)),this.opts.discriminator&&this.addKeyword(yy.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let I=this.opts.$data?this.$dataMetaSchema(Na,sy):Na;this.addMetaSchema(I,gW,!1),this.refs["http://json-schema.org/schema"]=gW}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(gW)?gW:void 0)}};WI.Ajv=Xb;cm.exports=WI=Xb;cm.exports.Ajv=Xb;Object.defineProperty(WI,"__esModule",{value:!0});WI.default=Xb;var ty=HZ();Object.defineProperty(WI,"KeywordCxt",{enumerable:!0,get:function(){return ty.KeywordCxt}});var Fb=B();Object.defineProperty(WI,"_",{enumerable:!0,get:function(){return Fb._}});Object.defineProperty(WI,"str",{enumerable:!0,get:function(){return Fb.str}});Object.defineProperty(WI,"stringify",{enumerable:!0,get:function(){return Fb.stringify}});Object.defineProperty(WI,"nil",{enumerable:!0,get:function(){return Fb.nil}});Object.defineProperty(WI,"Name",{enumerable:!0,get:function(){return Fb.Name}});Object.defineProperty(WI,"CodeGen",{enumerable:!0,get:function(){return Fb.CodeGen}});var Cy=YW();Object.defineProperty(WI,"ValidationError",{enumerable:!0,get:function(){return Cy.default}});var ey=pZ();Object.defineProperty(WI,"MissingRefError",{enumerable:!0,get:function(){return ey.default}})});var aa=J(JG=>{"use strict";Object.defineProperty(JG,"__esModule",{value:!0});JG.formatNames=JG.fastFormats=JG.fullFormats=void 0;function vG(G,I){return{validate:G,compare:I}}JG.fullFormats={date:vG(ha,mm),time:vG(Nm(!0),Vm),"date-time":vG(Ya(!0),Xa),"iso-time":vG(Nm(),Ra),"iso-date-time":vG(Ya(),Fa),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:zy,"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":/^(?:(?:[^\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,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,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:My,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:iy,int32:{type:"number",validate:By},int64:{type:"number",validate:ry},float:{type:"number",validate:Va},double:{type:"number",validate:Va},password:!0,binary:!0};JG.fastFormats={...JG.fullFormats,date:vG(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,mm),time:vG(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Vm),"date-time":vG(/^\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,Xa),"iso-time":vG(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Ra),"iso-date-time":vG(/^\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,Fa),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,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};JG.formatNames=Object.keys(JG.fullFormats);function gy(G){return G%4===0&&(G%100!==0||G%400===0)}var Ay=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ly=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ha(G){let I=Ay.exec(G);if(!I)return!1;let l=+I[1],b=+I[2],Z=+I[3];return b>=1&&b<=12&&Z>=1&&Z<=(b===2&&gy(l)?29:Ly[b])}function mm(G,I){if(G&&I)return G>I?1:G<I?-1:0}var dm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Nm(G){return function(l){let b=dm.exec(l);if(!b)return!1;let Z=+b[1],c=+b[2],W=+b[3],d=b[4],N=b[5]==="-"?-1:1,Y=+(b[6]||0),m=+(b[7]||0);if(Y>23||m>59||G&&!d)return!1;if(Z<=23&&c<=59&&W<60)return!0;let V=c-m*N,h=Z-Y*N-(V<0?1:0);return(h===23||h===-1)&&(V===59||V===-1)&&W<61}}function Vm(G,I){if(!(G&&I))return;let l=new Date("2020-01-01T"+G).valueOf(),b=new Date("2020-01-01T"+I).valueOf();if(l&&b)return l-b}function Ra(G,I){if(!(G&&I))return;let l=dm.exec(G),b=dm.exec(I);if(l&&b)return G=l[1]+l[2]+l[3],I=b[1]+b[2]+b[3],G>I?1:G<I?-1:0}var Ym=/t|\s/i;function Ya(G){let I=Nm(G);return function(b){let Z=b.split(Ym);return Z.length===2&&ha(Z[0])&&I(Z[1])}}function Xa(G,I){if(!(G&&I))return;let l=new Date(G).valueOf(),b=new Date(I).valueOf();if(l&&b)return l-b}function Fa(G,I){if(!(G&&I))return;let[l,b]=G.split(Ym),[Z,c]=I.split(Ym),W=mm(l,Z);if(W!==void 0)return W||Vm(b,c)}var ky=/\/|:/,oy=/^(?:[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 zy(G){return ky.test(G)&&oy.test(G)}var ma=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function iy(G){return ma.lastIndex=0,ma.test(G)}var xy=-(2**31),Uy=2**31-1;function By(G){return Number.isInteger(G)&&G<=Uy&&G>=xy}function ry(G){return Number.isInteger(G)}function Va(){return!0}var Oy=/[^\\]\\Z/;function My(G){if(Oy.test(G))return!1;try{return new RegExp(G),!0}catch{return!1}}});var Qa=J(ab=>{"use strict";Object.defineProperty(ab,"__esModule",{value:!0});ab.formatLimitDefinition=void 0;var jy=Wm(),VG=B(),Gl=VG.operators,AW={formatMaximum:{okStr:"<=",ok:Gl.LTE,fail:Gl.GT},formatMinimum:{okStr:">=",ok:Gl.GTE,fail:Gl.LT},formatExclusiveMaximum:{okStr:"<",ok:Gl.LT,fail:Gl.GTE},formatExclusiveMinimum:{okStr:">",ok:Gl.GT,fail:Gl.LTE}},Ky={message:({keyword:G,schemaCode:I})=>(0,VG.str)`should be ${AW[G].okStr} ${I}`,params:({keyword:G,schemaCode:I})=>(0,VG._)`{comparison: ${AW[G].okStr}, limit: ${I}}`};ab.formatLimitDefinition={keyword:Object.keys(AW),type:"string",schemaType:"string",$data:!0,error:Ky,code(G){let{gen:I,data:l,schemaCode:b,keyword:Z,it:c}=G,{opts:W,self:d}=c;if(!W.validateFormats)return;let N=new jy.KeywordCxt(c,d.RULES.all.format.definition,"format");N.$data?Y():m();function Y(){let h=I.scopeValue("formats",{ref:d.formats,code:W.code.formats}),R=I.const("fmt",(0,VG._)`${h}[${N.schemaCode}]`);G.fail$data((0,VG.or)((0,VG._)`typeof ${R} != "object"`,(0,VG._)`${R} instanceof RegExp`,(0,VG._)`typeof ${R}.compare != "function"`,V(R)))}function m(){let h=N.schema,R=d.formats[h];if(!R||R===!0)return;if(typeof R!="object"||R instanceof RegExp||typeof R.compare!="function")throw new Error(`"${Z}": format "${h}" does not define "compare" function`);let X=I.scopeValue("formats",{key:h,ref:R,code:W.code.formats?(0,VG._)`${W.code.formats}${(0,VG.getProperty)(h)}`:void 0});G.fail$data(V(X))}function V(h){return(0,VG._)`${h}.compare(${l}, ${b}) ${AW[Z].fail} 0`}},dependencies:["format"]};var Dy=G=>(G.addKeyword(ab.formatLimitDefinition),G);ab.default=Dy});var na=J((LZ,ua)=>{"use strict";Object.defineProperty(LZ,"__esModule",{value:!0});var Qb=aa(),Sy=Qa(),hm=B(),Ha=new hm.Name("fullFormats"),Ty=new hm.Name("fastFormats"),Rm=(G,I={keywords:!0})=>{if(Array.isArray(I))return pa(G,I,Qb.fullFormats,Ha),G;let[l,b]=I.mode==="fast"?[Qb.fastFormats,Ty]:[Qb.fullFormats,Ha],Z=I.formats||Qb.formatNames;return pa(G,Z,l,b),I.keywords&&(0,Sy.default)(G),G};Rm.get=(G,I="full")=>{let b=(I==="fast"?Qb.fastFormats:Qb.fullFormats)[G];if(!b)throw new Error(`Unknown format "${G}"`);return b};function pa(G,I,l,b){var Z,c;(Z=(c=G.opts.code).formats)!==null&&Z!==void 0||(c.formats=(0,hm._)`require("ajv-formats/dist/formats").${b}`);for(let W of I)G.addFormat(W,l[W])}ua.exports=LZ=Rm;Object.defineProperty(LZ,"__esModule",{value:!0});LZ.default=Rm});import{readFileSync as $y}from"fs";import{join as kZ}from"path";import{fileURLToPath as Is}from"url";var zl=class extends Error{providerId;constructor(I,l){super(`[${I}] ${l}`),this.providerId=I,this.name=this.constructor.name}},iZ=class extends zl{code="PROVIDER_NOT_FOUND";retryable=!1;constructor(I){super(I,`Provider not found: ${I}`)}},QI=class extends zl{code="PROVIDER_UNAVAILABLE";retryable=!1;constructor(I,l){super(I,`Provider unavailable: ${l||"not installed or not running"}`)}};var xG=class extends zl{timeoutMs;code="PROVIDER_TIMEOUT";retryable=!0;constructor(I,l){super(I,`Timeout after ${l}ms`),this.timeoutMs=l}},gI=class extends zl{code="PROVIDER_EXECUTION_ERROR";retryable=!0;constructor(I,l){super(I,`Execution error: ${l}`)}};import{spawn as Oa}from"child_process";var Ma=12e4;function hG(G){let{command:I,args:l,timeout:b=Ma,cwd:Z,env:c,stdin:W,maxBuffer:d=10485760}=G;return new Promise((N,Y)=>{let m=Oa(I,l,{cwd:Z,env:c?{...process.env,...c}:void 0,stdio:[W?"pipe":"ignore","pipe","pipe"],windowsHide:!0}),V="",h="",R=0,X=0,F=!1;m.stdout.on("data",p=>{R+=p.length,R<=d?V+=p.toString():F=!0}),m.stderr.on("data",p=>{X+=p.length,X<=d?h+=p.toString():F=!0}),W&&m.stdin&&(m.stdin.write(W),m.stdin.end());let H=()=>{m.kill("SIGTERM"),setTimeout(()=>{try{m.kill("SIGKILL")}catch{}},3e3),Y(new Error(`CLI timeout after ${b}ms of inactivity: ${I} ${l.join(" ")}`))},n=setTimeout(H,b),u=()=>{clearTimeout(n),n=setTimeout(H,b)};m.stdout.on("data",u),m.stderr.on("data",u),m.on("close",p=>{clearTimeout(n),N({stdout:V,stderr:h,exitCode:p??1,truncated:F})}),m.on("error",p=>{clearTimeout(n),Y(new Error(`CLI spawn error: ${p.message}`))})})}var OW={ollama:{tier:"tool"},"gemini-cli":{tier:"agent",maxComplexity:"complex"},"codex-cli":{tier:"agent",maxComplexity:"complex"}};function ja(G){return G<3?"simple":G<8?"moderate":G<=20?"complex":"advanced"}function nm(G,I,l){let b=OW[G]??{},Z=b.maxComplexity??"simple";return G==="ollama"&&l!==void 0&&(Z=ja(l)),{providerId:G,tier:b.tier??"tool",strengths:b.strengths??I.strengths,maxComplexity:Z}}var Ka={low:0,medium:.5,high:.7},Da={chat:"low",simple_review:"low",code_review:"medium",code_generation:"medium",design:"medium",writing:"medium",analysis:"medium",ideation:"medium",debate_turn:"medium",architecture:"high",cross_validate:"high",complex_refactor:"high"};function wm(G,I){return I?.[G]??Da[G]??"low"}function vm(G,I,l=Ka){return G>=l[I]}var xZ=class{providers=new Map;register(I){this.providers.set(I.id,I)}get(I){let l=this.providers.get(I);if(!l)throw new iZ(I);return l}getAll(){return[...this.providers.values()]}getAvailable(){return this.getAll().filter(I=>I.isAvailable())}getByCapability(I){return this.getAvailable().filter(l=>l.getCapabilities().strengths.includes(I))}has(I){return this.providers.has(I)}getCapability(I){let l=this.get(I);return nm(I,l.getCapabilities())}getByTier(I){return this.getAvailable().filter(l=>OW[l.id]?.tier===I)}getBestForTask(I,l,b,Z){let c=this.getAvailable();if(c.length===0)return;if(!l)return c[0];let W=b??wm(I),d=l.getQualityStats(30),N=new Map;for(let[h,R]of d){let X=h.split(":")[0],F=N.get(X)??{totalScore:0,count:0};F.totalScore+=R.avgScore*R.count,F.count+=R.count,N.set(X,F)}let Y=c.filter(h=>{let R=N.get(h.id);if(!R)return W==="low";let X=R.totalScore/R.count;return vm(X,W,Z)});if(Y.length===0)return;let m,V=-1;for(let h of Y){let R=`${h.id}:${I}`,X=d.get(R);X&&X.avgScore>V&&(V=X.avgScore,m=h)}return m??Y[0]}};var xI={};oZ(xI,{BRAND:()=>HQ,DIRTY:()=>ll,EMPTY_PATH:()=>fa,INVALID:()=>A,NEVER:()=>lH,OK:()=>EI,ParseStatus:()=>HI,Schema:()=>x,ZodAny:()=>rG,ZodArray:()=>tG,ZodBigInt:()=>Zl,ZodBoolean:()=>cl,ZodBranded:()=>ub,ZodCatch:()=>al,ZodDate:()=>Wl,ZodDefault:()=>Fl,ZodDiscriminatedUnion:()=>rZ,ZodEffects:()=>qI,ZodEnum:()=>Rl,ZodError:()=>zI,ZodFirstPartyTypeKind:()=>k,ZodFunction:()=>MZ,ZodIntersection:()=>ml,ZodIssueCode:()=>w,ZodLazy:()=>Vl,ZodLiteral:()=>hl,ZodMap:()=>Ol,ZodNaN:()=>jl,ZodNativeEnum:()=>Xl,ZodNever:()=>cG,ZodNull:()=>Nl,ZodNullable:()=>FG,ZodNumber:()=>bl,ZodObject:()=>iI,ZodOptional:()=>SI,ZodParsedType:()=>E,ZodPipeline:()=>nb,ZodPromise:()=>OG,ZodReadonly:()=>Ql,ZodRecord:()=>OZ,ZodSchema:()=>x,ZodSet:()=>Ml,ZodString:()=>BG,ZodSymbol:()=>Bl,ZodTransformer:()=>qI,ZodTuple:()=>XG,ZodType:()=>x,ZodUndefined:()=>dl,ZodUnion:()=>Yl,ZodUnknown:()=>sG,ZodVoid:()=>rl,addIssueToContext:()=>v,any:()=>sQ,array:()=>gQ,bigint:()=>wQ,boolean:()=>km,coerce:()=>GH,custom:()=>gm,date:()=>vQ,datetimeRegex:()=>Cm,defaultErrorMap:()=>EG,discriminatedUnion:()=>oQ,effect:()=>SQ,enum:()=>jQ,function:()=>rQ,getErrorMap:()=>il,getParsedType:()=>RG,instanceof:()=>uQ,intersection:()=>zQ,isAborted:()=>UZ,isAsync:()=>xl,isDirty:()=>BZ,isValid:()=>UG,late:()=>pQ,lazy:()=>OQ,literal:()=>MQ,makeIssue:()=>pb,map:()=>UQ,nan:()=>nQ,nativeEnum:()=>KQ,never:()=>CQ,null:()=>yQ,nullable:()=>qQ,number:()=>Lm,object:()=>AQ,objectUtil:()=>MW,oboolean:()=>IH,onumber:()=>$Q,optional:()=>TQ,ostring:()=>_Q,pipeline:()=>PQ,preprocess:()=>fQ,promise:()=>DQ,quotelessJson:()=>Sa,record:()=>xQ,set:()=>BQ,setErrorMap:()=>qa,strictObject:()=>LQ,string:()=>Am,symbol:()=>JQ,transformer:()=>SQ,tuple:()=>iQ,undefined:()=>EQ,union:()=>kQ,unknown:()=>tQ,util:()=>M,void:()=>eQ});var M;(function(G){G.assertEqual=Z=>{};function I(Z){}G.assertIs=I;function l(Z){throw new Error}G.assertNever=l,G.arrayToEnum=Z=>{let c={};for(let W of Z)c[W]=W;return c},G.getValidEnumValues=Z=>{let c=G.objectKeys(Z).filter(d=>typeof Z[Z[d]]!="number"),W={};for(let d of c)W[d]=Z[d];return G.objectValues(W)},G.objectValues=Z=>G.objectKeys(Z).map(function(c){return Z[c]}),G.objectKeys=typeof Object.keys=="function"?Z=>Object.keys(Z):Z=>{let c=[];for(let W in Z)Object.prototype.hasOwnProperty.call(Z,W)&&c.push(W);return c},G.find=(Z,c)=>{for(let W of Z)if(c(W))return W},G.isInteger=typeof Number.isInteger=="function"?Z=>Number.isInteger(Z):Z=>typeof Z=="number"&&Number.isFinite(Z)&&Math.floor(Z)===Z;function b(Z,c=" | "){return Z.map(W=>typeof W=="string"?`'${W}'`:W).join(c)}G.joinValues=b,G.jsonStringifyReplacer=(Z,c)=>typeof c=="bigint"?c.toString():c})(M||(M={}));var MW;(function(G){G.mergeShapes=(I,l)=>({...I,...l})})(MW||(MW={}));var E=M.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),RG=G=>{switch(typeof G){case"undefined":return E.undefined;case"string":return E.string;case"number":return Number.isNaN(G)?E.nan:E.number;case"boolean":return E.boolean;case"function":return E.function;case"bigint":return E.bigint;case"symbol":return E.symbol;case"object":return Array.isArray(G)?E.array:G===null?E.null:G.then&&typeof G.then=="function"&&G.catch&&typeof G.catch=="function"?E.promise:typeof Map<"u"&&G instanceof Map?E.map:typeof Set<"u"&&G instanceof Set?E.set:typeof Date<"u"&&G instanceof Date?E.date:E.object;default:return E.unknown}};var w=M.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"]),Sa=G=>JSON.stringify(G,null,2).replace(/"([^"]+)":/g,"$1:"),zI=class G extends Error{get errors(){return this.issues}constructor(I){super(),this.issues=[],this.addIssue=b=>{this.issues=[...this.issues,b]},this.addIssues=(b=[])=>{this.issues=[...this.issues,...b]};let l=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,l):this.__proto__=l,this.name="ZodError",this.issues=I}format(I){let l=I||function(c){return c.message},b={_errors:[]},Z=c=>{for(let W of c.issues)if(W.code==="invalid_union")W.unionErrors.map(Z);else if(W.code==="invalid_return_type")Z(W.returnTypeError);else if(W.code==="invalid_arguments")Z(W.argumentsError);else if(W.path.length===0)b._errors.push(l(W));else{let d=b,N=0;for(;N<W.path.length;){let Y=W.path[N];N===W.path.length-1?(d[Y]=d[Y]||{_errors:[]},d[Y]._errors.push(l(W))):d[Y]=d[Y]||{_errors:[]},d=d[Y],N++}}};return Z(this),b}static assert(I){if(!(I instanceof G))throw new Error(`Not a ZodError: ${I}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,M.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(I=l=>l.message){let l={},b=[];for(let Z of this.issues)if(Z.path.length>0){let c=Z.path[0];l[c]=l[c]||[],l[c].push(I(Z))}else b.push(I(Z));return{formErrors:b,fieldErrors:l}}get formErrors(){return this.flatten()}};zI.create=G=>new zI(G);var Ta=(G,I)=>{let l;switch(G.code){case w.invalid_type:G.received===E.undefined?l="Required":l=`Expected ${G.expected}, received ${G.received}`;break;case w.invalid_literal:l=`Invalid literal value, expected ${JSON.stringify(G.expected,M.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:l=`Unrecognized key(s) in object: ${M.joinValues(G.keys,", ")}`;break;case w.invalid_union:l="Invalid input";break;case w.invalid_union_discriminator:l=`Invalid discriminator value. Expected ${M.joinValues(G.options)}`;break;case w.invalid_enum_value:l=`Invalid enum value. Expected ${M.joinValues(G.options)}, received '${G.received}'`;break;case w.invalid_arguments:l="Invalid function arguments";break;case w.invalid_return_type:l="Invalid function return type";break;case w.invalid_date:l="Invalid date";break;case w.invalid_string:typeof G.validation=="object"?"includes"in G.validation?(l=`Invalid input: must include "${G.validation.includes}"`,typeof G.validation.position=="number"&&(l=`${l} at one or more positions greater than or equal to ${G.validation.position}`)):"startsWith"in G.validation?l=`Invalid input: must start with "${G.validation.startsWith}"`:"endsWith"in G.validation?l=`Invalid input: must end with "${G.validation.endsWith}"`:M.assertNever(G.validation):G.validation!=="regex"?l=`Invalid ${G.validation}`:l="Invalid";break;case w.too_small:G.type==="array"?l=`Array must contain ${G.exact?"exactly":G.inclusive?"at least":"more than"} ${G.minimum} element(s)`:G.type==="string"?l=`String must contain ${G.exact?"exactly":G.inclusive?"at least":"over"} ${G.minimum} character(s)`:G.type==="number"?l=`Number must be ${G.exact?"exactly equal to ":G.inclusive?"greater than or equal to ":"greater than "}${G.minimum}`:G.type==="bigint"?l=`Number must be ${G.exact?"exactly equal to ":G.inclusive?"greater than or equal to ":"greater than "}${G.minimum}`:G.type==="date"?l=`Date must be ${G.exact?"exactly equal to ":G.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(G.minimum))}`:l="Invalid input";break;case w.too_big:G.type==="array"?l=`Array must contain ${G.exact?"exactly":G.inclusive?"at most":"less than"} ${G.maximum} element(s)`:G.type==="string"?l=`String must contain ${G.exact?"exactly":G.inclusive?"at most":"under"} ${G.maximum} character(s)`:G.type==="number"?l=`Number must be ${G.exact?"exactly":G.inclusive?"less than or equal to":"less than"} ${G.maximum}`:G.type==="bigint"?l=`BigInt must be ${G.exact?"exactly":G.inclusive?"less than or equal to":"less than"} ${G.maximum}`:G.type==="date"?l=`Date must be ${G.exact?"exactly":G.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(G.maximum))}`:l="Invalid input";break;case w.custom:l="Invalid input";break;case w.invalid_intersection_types:l="Intersection results could not be merged";break;case w.not_multiple_of:l=`Number must be a multiple of ${G.multipleOf}`;break;case w.not_finite:l="Number must be finite";break;default:l=I.defaultError,M.assertNever(G)}return{message:l}},EG=Ta;var Jm=EG;function qa(G){Jm=G}function il(){return Jm}var pb=G=>{let{data:I,path:l,errorMaps:b,issueData:Z}=G,c=[...l,...Z.path||[]],W={...Z,path:c};if(Z.message!==void 0)return{...Z,path:c,message:Z.message};let d="",N=b.filter(Y=>!!Y).slice().reverse();for(let Y of N)d=Y(W,{data:I,defaultError:d}).message;return{...Z,path:c,message:d}},fa=[];function v(G,I){let l=il(),b=pb({issueData:I,data:G.data,path:G.path,errorMaps:[G.common.contextualErrorMap,G.schemaErrorMap,l,l===EG?void 0:EG].filter(Z=>!!Z)});G.common.issues.push(b)}var HI=class G{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(I,l){let b=[];for(let Z of l){if(Z.status==="aborted")return A;Z.status==="dirty"&&I.dirty(),b.push(Z.value)}return{status:I.value,value:b}}static async mergeObjectAsync(I,l){let b=[];for(let Z of l){let c=await Z.key,W=await Z.value;b.push({key:c,value:W})}return G.mergeObjectSync(I,b)}static mergeObjectSync(I,l){let b={};for(let Z of l){let{key:c,value:W}=Z;if(c.status==="aborted"||W.status==="aborted")return A;c.status==="dirty"&&I.dirty(),W.status==="dirty"&&I.dirty(),c.value!=="__proto__"&&(typeof W.value<"u"||Z.alwaysSet)&&(b[c.value]=W.value)}return{status:I.value,value:b}}},A=Object.freeze({status:"aborted"}),ll=G=>({status:"dirty",value:G}),EI=G=>({status:"valid",value:G}),UZ=G=>G.status==="aborted",BZ=G=>G.status==="dirty",UG=G=>G.status==="valid",xl=G=>typeof Promise<"u"&&G instanceof Promise;var s;(function(G){G.errToObj=I=>typeof I=="string"?{message:I}:I||{},G.toString=I=>typeof I=="string"?I:I?.message})(s||(s={}));var TI=class{constructor(I,l,b,Z){this._cachedPath=[],this.parent=I,this.data=l,this._path=b,this._key=Z}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Em=(G,I)=>{if(UG(I))return{success:!0,data:I.value};if(!G.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let l=new zI(G.common.issues);return this._error=l,this._error}}};function z(G){if(!G)return{};let{errorMap:I,invalid_type_error:l,required_error:b,description:Z}=G;if(I&&(l||b))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return I?{errorMap:I,description:Z}:{errorMap:(W,d)=>{let{message:N}=G;return W.code==="invalid_enum_value"?{message:N??d.defaultError}:typeof d.data>"u"?{message:N??b??d.defaultError}:W.code!=="invalid_type"?{message:d.defaultError}:{message:N??l??d.defaultError}},description:Z}}var x=class{get description(){return this._def.description}_getType(I){return RG(I.data)}_getOrReturnCtx(I,l){return l||{common:I.parent.common,data:I.data,parsedType:RG(I.data),schemaErrorMap:this._def.errorMap,path:I.path,parent:I.parent}}_processInputParams(I){return{status:new HI,ctx:{common:I.parent.common,data:I.data,parsedType:RG(I.data),schemaErrorMap:this._def.errorMap,path:I.path,parent:I.parent}}}_parseSync(I){let l=this._parse(I);if(xl(l))throw new Error("Synchronous parse encountered promise.");return l}_parseAsync(I){let l=this._parse(I);return Promise.resolve(l)}parse(I,l){let b=this.safeParse(I,l);if(b.success)return b.data;throw b.error}safeParse(I,l){let b={common:{issues:[],async:l?.async??!1,contextualErrorMap:l?.errorMap},path:l?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:RG(I)},Z=this._parseSync({data:I,path:b.path,parent:b});return Em(b,Z)}"~validate"(I){let l={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:RG(I)};if(!this["~standard"].async)try{let b=this._parseSync({data:I,path:[],parent:l});return UG(b)?{value:b.value}:{issues:l.common.issues}}catch(b){b?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),l.common={issues:[],async:!0}}return this._parseAsync({data:I,path:[],parent:l}).then(b=>UG(b)?{value:b.value}:{issues:l.common.issues})}async parseAsync(I,l){let b=await this.safeParseAsync(I,l);if(b.success)return b.data;throw b.error}async safeParseAsync(I,l){let b={common:{issues:[],contextualErrorMap:l?.errorMap,async:!0},path:l?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:I,parsedType:RG(I)},Z=this._parse({data:I,path:b.path,parent:b}),c=await(xl(Z)?Z:Promise.resolve(Z));return Em(b,c)}refine(I,l){let b=Z=>typeof l=="string"||typeof l>"u"?{message:l}:typeof l=="function"?l(Z):l;return this._refinement((Z,c)=>{let W=I(Z),d=()=>c.addIssue({code:w.custom,...b(Z)});return typeof Promise<"u"&&W instanceof Promise?W.then(N=>N?!0:(d(),!1)):W?!0:(d(),!1)})}refinement(I,l){return this._refinement((b,Z)=>I(b)?!0:(Z.addIssue(typeof l=="function"?l(b,Z):l),!1))}_refinement(I){return new qI({schema:this,typeName:k.ZodEffects,effect:{type:"refinement",refinement:I}})}superRefine(I){return this._refinement(I)}constructor(I){this.spa=this.safeParseAsync,this._def=I,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:l=>this["~validate"](l)}}optional(){return SI.create(this,this._def)}nullable(){return FG.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return tG.create(this)}promise(){return OG.create(this,this._def)}or(I){return Yl.create([this,I],this._def)}and(I){return ml.create(this,I,this._def)}transform(I){return new qI({...z(this._def),schema:this,typeName:k.ZodEffects,effect:{type:"transform",transform:I}})}default(I){let l=typeof I=="function"?I:()=>I;return new Fl({...z(this._def),innerType:this,defaultValue:l,typeName:k.ZodDefault})}brand(){return new ub({typeName:k.ZodBranded,type:this,...z(this._def)})}catch(I){let l=typeof I=="function"?I:()=>I;return new al({...z(this._def),innerType:this,catchValue:l,typeName:k.ZodCatch})}describe(I){let l=this.constructor;return new l({...this._def,description:I})}pipe(I){return nb.create(this,I)}readonly(){return Ql.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Pa=/^c[^\s-]{8,}$/i,_a=/^[0-9a-z]+$/,$a=/^[0-9A-HJKMNP-TV-Z]{26}$/i,IQ=/^[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,GQ=/^[a-z0-9_-]{21}$/i,lQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bQ=/^[-+]?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)?)??$/,ZQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",jW,WQ=/^(?:(?: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])$/,dQ=/^(?:(?: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])$/,NQ=/^(([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]))$/,YQ=/^(([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])$/,mQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,VQ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,sm="((\\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])))",hQ=new RegExp(`^${sm}$`);function tm(G){let I="[0-5]\\d";G.precision?I=`${I}\\.\\d{${G.precision}}`:G.precision==null&&(I=`${I}(\\.\\d+)?`);let l=G.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${I})${l}`}function RQ(G){return new RegExp(`^${tm(G)}$`)}function Cm(G){let I=`${sm}T${tm(G)}`,l=[];return l.push(G.local?"Z?":"Z"),G.offset&&l.push("([+-]\\d{2}:?\\d{2})"),I=`${I}(${l.join("|")})`,new RegExp(`^${I}$`)}function XQ(G,I){return!!((I==="v4"||!I)&&WQ.test(G)||(I==="v6"||!I)&&NQ.test(G))}function FQ(G,I){if(!lQ.test(G))return!1;try{let[l]=G.split(".");if(!l)return!1;let b=l.replace(/-/g,"+").replace(/_/g,"/").padEnd(l.length+(4-l.length%4)%4,"="),Z=JSON.parse(atob(b));return!(typeof Z!="object"||Z===null||"typ"in Z&&Z?.typ!=="JWT"||!Z.alg||I&&Z.alg!==I)}catch{return!1}}function aQ(G,I){return!!((I==="v4"||!I)&&dQ.test(G)||(I==="v6"||!I)&&YQ.test(G))}var BG=class G extends x{_parse(I){if(this._def.coerce&&(I.data=String(I.data)),this._getType(I)!==E.string){let c=this._getOrReturnCtx(I);return v(c,{code:w.invalid_type,expected:E.string,received:c.parsedType}),A}let b=new HI,Z;for(let c of this._def.checks)if(c.kind==="min")I.data.length<c.value&&(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),b.dirty());else if(c.kind==="max")I.data.length>c.value&&(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!1,message:c.message}),b.dirty());else if(c.kind==="length"){let W=I.data.length>c.value,d=I.data.length<c.value;(W||d)&&(Z=this._getOrReturnCtx(I,Z),W?v(Z,{code:w.too_big,maximum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}):d&&v(Z,{code:w.too_small,minimum:c.value,type:"string",inclusive:!0,exact:!0,message:c.message}),b.dirty())}else if(c.kind==="email")ZQ.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"email",code:w.invalid_string,message:c.message}),b.dirty());else if(c.kind==="emoji")jW||(jW=new RegExp(cQ,"u")),jW.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"emoji",code:w.invalid_string,message:c.message}),b.dirty());else if(c.kind==="uuid")IQ.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"uuid",code:w.invalid_string,message:c.message}),b.dirty());else if(c.kind==="nanoid")GQ.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"nanoid",code:w.invalid_string,message:c.message}),b.dirty());else if(c.kind==="cuid")Pa.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"cuid",code:w.invalid_string,message:c.message}),b.dirty());else if(c.kind==="cuid2")_a.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"cuid2",code:w.invalid_string,message:c.message}),b.dirty());else if(c.kind==="ulid")$a.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"ulid",code:w.invalid_string,message:c.message}),b.dirty());else if(c.kind==="url")try{new URL(I.data)}catch{Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"url",code:w.invalid_string,message:c.message}),b.dirty()}else c.kind==="regex"?(c.regex.lastIndex=0,c.regex.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"regex",code:w.invalid_string,message:c.message}),b.dirty())):c.kind==="trim"?I.data=I.data.trim():c.kind==="includes"?I.data.includes(c.value,c.position)||(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.invalid_string,validation:{includes:c.value,position:c.position},message:c.message}),b.dirty()):c.kind==="toLowerCase"?I.data=I.data.toLowerCase():c.kind==="toUpperCase"?I.data=I.data.toUpperCase():c.kind==="startsWith"?I.data.startsWith(c.value)||(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.invalid_string,validation:{startsWith:c.value},message:c.message}),b.dirty()):c.kind==="endsWith"?I.data.endsWith(c.value)||(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.invalid_string,validation:{endsWith:c.value},message:c.message}),b.dirty()):c.kind==="datetime"?Cm(c).test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.invalid_string,validation:"datetime",message:c.message}),b.dirty()):c.kind==="date"?hQ.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.invalid_string,validation:"date",message:c.message}),b.dirty()):c.kind==="time"?RQ(c).test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.invalid_string,validation:"time",message:c.message}),b.dirty()):c.kind==="duration"?bQ.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"duration",code:w.invalid_string,message:c.message}),b.dirty()):c.kind==="ip"?XQ(I.data,c.version)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"ip",code:w.invalid_string,message:c.message}),b.dirty()):c.kind==="jwt"?FQ(I.data,c.alg)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"jwt",code:w.invalid_string,message:c.message}),b.dirty()):c.kind==="cidr"?aQ(I.data,c.version)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"cidr",code:w.invalid_string,message:c.message}),b.dirty()):c.kind==="base64"?mQ.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"base64",code:w.invalid_string,message:c.message}),b.dirty()):c.kind==="base64url"?VQ.test(I.data)||(Z=this._getOrReturnCtx(I,Z),v(Z,{validation:"base64url",code:w.invalid_string,message:c.message}),b.dirty()):M.assertNever(c);return{status:b.value,value:I.data}}_regex(I,l,b){return this.refinement(Z=>I.test(Z),{validation:l,code:w.invalid_string,...s.errToObj(b)})}_addCheck(I){return new G({...this._def,checks:[...this._def.checks,I]})}email(I){return this._addCheck({kind:"email",...s.errToObj(I)})}url(I){return this._addCheck({kind:"url",...s.errToObj(I)})}emoji(I){return this._addCheck({kind:"emoji",...s.errToObj(I)})}uuid(I){return this._addCheck({kind:"uuid",...s.errToObj(I)})}nanoid(I){return this._addCheck({kind:"nanoid",...s.errToObj(I)})}cuid(I){return this._addCheck({kind:"cuid",...s.errToObj(I)})}cuid2(I){return this._addCheck({kind:"cuid2",...s.errToObj(I)})}ulid(I){return this._addCheck({kind:"ulid",...s.errToObj(I)})}base64(I){return this._addCheck({kind:"base64",...s.errToObj(I)})}base64url(I){return this._addCheck({kind:"base64url",...s.errToObj(I)})}jwt(I){return this._addCheck({kind:"jwt",...s.errToObj(I)})}ip(I){return this._addCheck({kind:"ip",...s.errToObj(I)})}cidr(I){return this._addCheck({kind:"cidr",...s.errToObj(I)})}datetime(I){return typeof I=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:I}):this._addCheck({kind:"datetime",precision:typeof I?.precision>"u"?null:I?.precision,offset:I?.offset??!1,local:I?.local??!1,...s.errToObj(I?.message)})}date(I){return this._addCheck({kind:"date",message:I})}time(I){return typeof I=="string"?this._addCheck({kind:"time",precision:null,message:I}):this._addCheck({kind:"time",precision:typeof I?.precision>"u"?null:I?.precision,...s.errToObj(I?.message)})}duration(I){return this._addCheck({kind:"duration",...s.errToObj(I)})}regex(I,l){return this._addCheck({kind:"regex",regex:I,...s.errToObj(l)})}includes(I,l){return this._addCheck({kind:"includes",value:I,position:l?.position,...s.errToObj(l?.message)})}startsWith(I,l){return this._addCheck({kind:"startsWith",value:I,...s.errToObj(l)})}endsWith(I,l){return this._addCheck({kind:"endsWith",value:I,...s.errToObj(l)})}min(I,l){return this._addCheck({kind:"min",value:I,...s.errToObj(l)})}max(I,l){return this._addCheck({kind:"max",value:I,...s.errToObj(l)})}length(I,l){return this._addCheck({kind:"length",value:I,...s.errToObj(l)})}nonempty(I){return this.min(1,s.errToObj(I))}trim(){return new G({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new G({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(I=>I.kind==="datetime")}get isDate(){return!!this._def.checks.find(I=>I.kind==="date")}get isTime(){return!!this._def.checks.find(I=>I.kind==="time")}get isDuration(){return!!this._def.checks.find(I=>I.kind==="duration")}get isEmail(){return!!this._def.checks.find(I=>I.kind==="email")}get isURL(){return!!this._def.checks.find(I=>I.kind==="url")}get isEmoji(){return!!this._def.checks.find(I=>I.kind==="emoji")}get isUUID(){return!!this._def.checks.find(I=>I.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(I=>I.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(I=>I.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(I=>I.kind==="cuid2")}get isULID(){return!!this._def.checks.find(I=>I.kind==="ulid")}get isIP(){return!!this._def.checks.find(I=>I.kind==="ip")}get isCIDR(){return!!this._def.checks.find(I=>I.kind==="cidr")}get isBase64(){return!!this._def.checks.find(I=>I.kind==="base64")}get isBase64url(){return!!this._def.checks.find(I=>I.kind==="base64url")}get minLength(){let I=null;for(let l of this._def.checks)l.kind==="min"&&(I===null||l.value>I)&&(I=l.value);return I}get maxLength(){let I=null;for(let l of this._def.checks)l.kind==="max"&&(I===null||l.value<I)&&(I=l.value);return I}};BG.create=G=>new BG({checks:[],typeName:k.ZodString,coerce:G?.coerce??!1,...z(G)});function QQ(G,I){let l=(G.toString().split(".")[1]||"").length,b=(I.toString().split(".")[1]||"").length,Z=l>b?l:b,c=Number.parseInt(G.toFixed(Z).replace(".","")),W=Number.parseInt(I.toFixed(Z).replace(".",""));return c%W/10**Z}var bl=class G extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(I){if(this._def.coerce&&(I.data=Number(I.data)),this._getType(I)!==E.number){let c=this._getOrReturnCtx(I);return v(c,{code:w.invalid_type,expected:E.number,received:c.parsedType}),A}let b,Z=new HI;for(let c of this._def.checks)c.kind==="int"?M.isInteger(I.data)||(b=this._getOrReturnCtx(I,b),v(b,{code:w.invalid_type,expected:"integer",received:"float",message:c.message}),Z.dirty()):c.kind==="min"?(c.inclusive?I.data<c.value:I.data<=c.value)&&(b=this._getOrReturnCtx(I,b),v(b,{code:w.too_small,minimum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),Z.dirty()):c.kind==="max"?(c.inclusive?I.data>c.value:I.data>=c.value)&&(b=this._getOrReturnCtx(I,b),v(b,{code:w.too_big,maximum:c.value,type:"number",inclusive:c.inclusive,exact:!1,message:c.message}),Z.dirty()):c.kind==="multipleOf"?QQ(I.data,c.value)!==0&&(b=this._getOrReturnCtx(I,b),v(b,{code:w.not_multiple_of,multipleOf:c.value,message:c.message}),Z.dirty()):c.kind==="finite"?Number.isFinite(I.data)||(b=this._getOrReturnCtx(I,b),v(b,{code:w.not_finite,message:c.message}),Z.dirty()):M.assertNever(c);return{status:Z.value,value:I.data}}gte(I,l){return this.setLimit("min",I,!0,s.toString(l))}gt(I,l){return this.setLimit("min",I,!1,s.toString(l))}lte(I,l){return this.setLimit("max",I,!0,s.toString(l))}lt(I,l){return this.setLimit("max",I,!1,s.toString(l))}setLimit(I,l,b,Z){return new G({...this._def,checks:[...this._def.checks,{kind:I,value:l,inclusive:b,message:s.toString(Z)}]})}_addCheck(I){return new G({...this._def,checks:[...this._def.checks,I]})}int(I){return this._addCheck({kind:"int",message:s.toString(I)})}positive(I){return this._addCheck({kind:"min",value:0,inclusive:!1,message:s.toString(I)})}negative(I){return this._addCheck({kind:"max",value:0,inclusive:!1,message:s.toString(I)})}nonpositive(I){return this._addCheck({kind:"max",value:0,inclusive:!0,message:s.toString(I)})}nonnegative(I){return this._addCheck({kind:"min",value:0,inclusive:!0,message:s.toString(I)})}multipleOf(I,l){return this._addCheck({kind:"multipleOf",value:I,message:s.toString(l)})}finite(I){return this._addCheck({kind:"finite",message:s.toString(I)})}safe(I){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:s.toString(I)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:s.toString(I)})}get minValue(){let I=null;for(let l of this._def.checks)l.kind==="min"&&(I===null||l.value>I)&&(I=l.value);return I}get maxValue(){let I=null;for(let l of this._def.checks)l.kind==="max"&&(I===null||l.value<I)&&(I=l.value);return I}get isInt(){return!!this._def.checks.find(I=>I.kind==="int"||I.kind==="multipleOf"&&M.isInteger(I.value))}get isFinite(){let I=null,l=null;for(let b of this._def.checks){if(b.kind==="finite"||b.kind==="int"||b.kind==="multipleOf")return!0;b.kind==="min"?(l===null||b.value>l)&&(l=b.value):b.kind==="max"&&(I===null||b.value<I)&&(I=b.value)}return Number.isFinite(l)&&Number.isFinite(I)}};bl.create=G=>new bl({checks:[],typeName:k.ZodNumber,coerce:G?.coerce||!1,...z(G)});var Zl=class G extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(I){if(this._def.coerce)try{I.data=BigInt(I.data)}catch{return this._getInvalidInput(I)}if(this._getType(I)!==E.bigint)return this._getInvalidInput(I);let b,Z=new HI;for(let c of this._def.checks)c.kind==="min"?(c.inclusive?I.data<c.value:I.data<=c.value)&&(b=this._getOrReturnCtx(I,b),v(b,{code:w.too_small,type:"bigint",minimum:c.value,inclusive:c.inclusive,message:c.message}),Z.dirty()):c.kind==="max"?(c.inclusive?I.data>c.value:I.data>=c.value)&&(b=this._getOrReturnCtx(I,b),v(b,{code:w.too_big,type:"bigint",maximum:c.value,inclusive:c.inclusive,message:c.message}),Z.dirty()):c.kind==="multipleOf"?I.data%c.value!==BigInt(0)&&(b=this._getOrReturnCtx(I,b),v(b,{code:w.not_multiple_of,multipleOf:c.value,message:c.message}),Z.dirty()):M.assertNever(c);return{status:Z.value,value:I.data}}_getInvalidInput(I){let l=this._getOrReturnCtx(I);return v(l,{code:w.invalid_type,expected:E.bigint,received:l.parsedType}),A}gte(I,l){return this.setLimit("min",I,!0,s.toString(l))}gt(I,l){return this.setLimit("min",I,!1,s.toString(l))}lte(I,l){return this.setLimit("max",I,!0,s.toString(l))}lt(I,l){return this.setLimit("max",I,!1,s.toString(l))}setLimit(I,l,b,Z){return new G({...this._def,checks:[...this._def.checks,{kind:I,value:l,inclusive:b,message:s.toString(Z)}]})}_addCheck(I){return new G({...this._def,checks:[...this._def.checks,I]})}positive(I){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:s.toString(I)})}negative(I){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:s.toString(I)})}nonpositive(I){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:s.toString(I)})}nonnegative(I){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:s.toString(I)})}multipleOf(I,l){return this._addCheck({kind:"multipleOf",value:I,message:s.toString(l)})}get minValue(){let I=null;for(let l of this._def.checks)l.kind==="min"&&(I===null||l.value>I)&&(I=l.value);return I}get maxValue(){let I=null;for(let l of this._def.checks)l.kind==="max"&&(I===null||l.value<I)&&(I=l.value);return I}};Zl.create=G=>new Zl({checks:[],typeName:k.ZodBigInt,coerce:G?.coerce??!1,...z(G)});var cl=class extends x{_parse(I){if(this._def.coerce&&(I.data=!!I.data),this._getType(I)!==E.boolean){let b=this._getOrReturnCtx(I);return v(b,{code:w.invalid_type,expected:E.boolean,received:b.parsedType}),A}return EI(I.data)}};cl.create=G=>new cl({typeName:k.ZodBoolean,coerce:G?.coerce||!1,...z(G)});var Wl=class G extends x{_parse(I){if(this._def.coerce&&(I.data=new Date(I.data)),this._getType(I)!==E.date){let c=this._getOrReturnCtx(I);return v(c,{code:w.invalid_type,expected:E.date,received:c.parsedType}),A}if(Number.isNaN(I.data.getTime())){let c=this._getOrReturnCtx(I);return v(c,{code:w.invalid_date}),A}let b=new HI,Z;for(let c of this._def.checks)c.kind==="min"?I.data.getTime()<c.value&&(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.too_small,message:c.message,inclusive:!0,exact:!1,minimum:c.value,type:"date"}),b.dirty()):c.kind==="max"?I.data.getTime()>c.value&&(Z=this._getOrReturnCtx(I,Z),v(Z,{code:w.too_big,message:c.message,inclusive:!0,exact:!1,maximum:c.value,type:"date"}),b.dirty()):M.assertNever(c);return{status:b.value,value:new Date(I.data.getTime())}}_addCheck(I){return new G({...this._def,checks:[...this._def.checks,I]})}min(I,l){return this._addCheck({kind:"min",value:I.getTime(),message:s.toString(l)})}max(I,l){return this._addCheck({kind:"max",value:I.getTime(),message:s.toString(l)})}get minDate(){let I=null;for(let l of this._def.checks)l.kind==="min"&&(I===null||l.value>I)&&(I=l.value);return I!=null?new Date(I):null}get maxDate(){let I=null;for(let l of this._def.checks)l.kind==="max"&&(I===null||l.value<I)&&(I=l.value);return I!=null?new Date(I):null}};Wl.create=G=>new Wl({checks:[],coerce:G?.coerce||!1,typeName:k.ZodDate,...z(G)});var Bl=class extends x{_parse(I){if(this._getType(I)!==E.symbol){let b=this._getOrReturnCtx(I);return v(b,{code:w.invalid_type,expected:E.symbol,received:b.parsedType}),A}return EI(I.data)}};Bl.create=G=>new Bl({typeName:k.ZodSymbol,...z(G)});var dl=class extends x{_parse(I){if(this._getType(I)!==E.undefined){let b=this._getOrReturnCtx(I);return v(b,{code:w.invalid_type,expected:E.undefined,received:b.parsedType}),A}return EI(I.data)}};dl.create=G=>new dl({typeName:k.ZodUndefined,...z(G)});var Nl=class extends x{_parse(I){if(this._getType(I)!==E.null){let b=this._getOrReturnCtx(I);return v(b,{code:w.invalid_type,expected:E.null,received:b.parsedType}),A}return EI(I.data)}};Nl.create=G=>new Nl({typeName:k.ZodNull,...z(G)});var rG=class extends x{constructor(){super(...arguments),this._any=!0}_parse(I){return EI(I.data)}};rG.create=G=>new rG({typeName:k.ZodAny,...z(G)});var sG=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(I){return EI(I.data)}};sG.create=G=>new sG({typeName:k.ZodUnknown,...z(G)});var cG=class extends x{_parse(I){let l=this._getOrReturnCtx(I);return v(l,{code:w.invalid_type,expected:E.never,received:l.parsedType}),A}};cG.create=G=>new cG({typeName:k.ZodNever,...z(G)});var rl=class extends x{_parse(I){if(this._getType(I)!==E.undefined){let b=this._getOrReturnCtx(I);return v(b,{code:w.invalid_type,expected:E.void,received:b.parsedType}),A}return EI(I.data)}};rl.create=G=>new rl({typeName:k.ZodVoid,...z(G)});var tG=class G extends x{_parse(I){let{ctx:l,status:b}=this._processInputParams(I),Z=this._def;if(l.parsedType!==E.array)return v(l,{code:w.invalid_type,expected:E.array,received:l.parsedType}),A;if(Z.exactLength!==null){let W=l.data.length>Z.exactLength.value,d=l.data.length<Z.exactLength.value;(W||d)&&(v(l,{code:W?w.too_big:w.too_small,minimum:d?Z.exactLength.value:void 0,maximum:W?Z.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:Z.exactLength.message}),b.dirty())}if(Z.minLength!==null&&l.data.length<Z.minLength.value&&(v(l,{code:w.too_small,minimum:Z.minLength.value,type:"array",inclusive:!0,exact:!1,message:Z.minLength.message}),b.dirty()),Z.maxLength!==null&&l.data.length>Z.maxLength.value&&(v(l,{code:w.too_big,maximum:Z.maxLength.value,type:"array",inclusive:!0,exact:!1,message:Z.maxLength.message}),b.dirty()),l.common.async)return Promise.all([...l.data].map((W,d)=>Z.type._parseAsync(new TI(l,W,l.path,d)))).then(W=>HI.mergeArray(b,W));let c=[...l.data].map((W,d)=>Z.type._parseSync(new TI(l,W,l.path,d)));return HI.mergeArray(b,c)}get element(){return this._def.type}min(I,l){return new G({...this._def,minLength:{value:I,message:s.toString(l)}})}max(I,l){return new G({...this._def,maxLength:{value:I,message:s.toString(l)}})}length(I,l){return new G({...this._def,exactLength:{value:I,message:s.toString(l)}})}nonempty(I){return this.min(1,I)}};tG.create=(G,I)=>new tG({type:G,minLength:null,maxLength:null,exactLength:null,typeName:k.ZodArray,...z(I)});function Ul(G){if(G instanceof iI){let I={};for(let l in G.shape){let b=G.shape[l];I[l]=SI.create(Ul(b))}return new iI({...G._def,shape:()=>I})}else return G instanceof tG?new tG({...G._def,type:Ul(G.element)}):G instanceof SI?SI.create(Ul(G.unwrap())):G instanceof FG?FG.create(Ul(G.unwrap())):G instanceof XG?XG.create(G.items.map(I=>Ul(I))):G}var iI=class G extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let I=this._def.shape(),l=M.objectKeys(I);return this._cached={shape:I,keys:l},this._cached}_parse(I){if(this._getType(I)!==E.object){let Y=this._getOrReturnCtx(I);return v(Y,{code:w.invalid_type,expected:E.object,received:Y.parsedType}),A}let{status:b,ctx:Z}=this._processInputParams(I),{shape:c,keys:W}=this._getCached(),d=[];if(!(this._def.catchall instanceof cG&&this._def.unknownKeys==="strip"))for(let Y in Z.data)W.includes(Y)||d.push(Y);let N=[];for(let Y of W){let m=c[Y],V=Z.data[Y];N.push({key:{status:"valid",value:Y},value:m._parse(new TI(Z,V,Z.path,Y)),alwaysSet:Y in Z.data})}if(this._def.catchall instanceof cG){let Y=this._def.unknownKeys;if(Y==="passthrough")for(let m of d)N.push({key:{status:"valid",value:m},value:{status:"valid",value:Z.data[m]}});else if(Y==="strict")d.length>0&&(v(Z,{code:w.unrecognized_keys,keys:d}),b.dirty());else if(Y!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Y=this._def.catchall;for(let m of d){let V=Z.data[m];N.push({key:{status:"valid",value:m},value:Y._parse(new TI(Z,V,Z.path,m)),alwaysSet:m in Z.data})}}return Z.common.async?Promise.resolve().then(async()=>{let Y=[];for(let m of N){let V=await m.key,h=await m.value;Y.push({key:V,value:h,alwaysSet:m.alwaysSet})}return Y}).then(Y=>HI.mergeObjectSync(b,Y)):HI.mergeObjectSync(b,N)}get shape(){return this._def.shape()}strict(I){return s.errToObj,new G({...this._def,unknownKeys:"strict",...I!==void 0?{errorMap:(l,b)=>{let Z=this._def.errorMap?.(l,b).message??b.defaultError;return l.code==="unrecognized_keys"?{message:s.errToObj(I).message??Z}:{message:Z}}}:{}})}strip(){return new G({...this._def,unknownKeys:"strip"})}passthrough(){return new G({...this._def,unknownKeys:"passthrough"})}extend(I){return new G({...this._def,shape:()=>({...this._def.shape(),...I})})}merge(I){return new G({unknownKeys:I._def.unknownKeys,catchall:I._def.catchall,shape:()=>({...this._def.shape(),...I._def.shape()}),typeName:k.ZodObject})}setKey(I,l){return this.augment({[I]:l})}catchall(I){return new G({...this._def,catchall:I})}pick(I){let l={};for(let b of M.objectKeys(I))I[b]&&this.shape[b]&&(l[b]=this.shape[b]);return new G({...this._def,shape:()=>l})}omit(I){let l={};for(let b of M.objectKeys(this.shape))I[b]||(l[b]=this.shape[b]);return new G({...this._def,shape:()=>l})}deepPartial(){return Ul(this)}partial(I){let l={};for(let b of M.objectKeys(this.shape)){let Z=this.shape[b];I&&!I[b]?l[b]=Z:l[b]=Z.optional()}return new G({...this._def,shape:()=>l})}required(I){let l={};for(let b of M.objectKeys(this.shape))if(I&&!I[b])l[b]=this.shape[b];else{let c=this.shape[b];for(;c instanceof SI;)c=c._def.innerType;l[b]=c}return new G({...this._def,shape:()=>l})}keyof(){return em(M.objectKeys(this.shape))}};iI.create=(G,I)=>new iI({shape:()=>G,unknownKeys:"strip",catchall:cG.create(),typeName:k.ZodObject,...z(I)});iI.strictCreate=(G,I)=>new iI({shape:()=>G,unknownKeys:"strict",catchall:cG.create(),typeName:k.ZodObject,...z(I)});iI.lazycreate=(G,I)=>new iI({shape:G,unknownKeys:"strip",catchall:cG.create(),typeName:k.ZodObject,...z(I)});var Yl=class extends x{_parse(I){let{ctx:l}=this._processInputParams(I),b=this._def.options;function Z(c){for(let d of c)if(d.result.status==="valid")return d.result;for(let d of c)if(d.result.status==="dirty")return l.common.issues.push(...d.ctx.common.issues),d.result;let W=c.map(d=>new zI(d.ctx.common.issues));return v(l,{code:w.invalid_union,unionErrors:W}),A}if(l.common.async)return Promise.all(b.map(async c=>{let W={...l,common:{...l.common,issues:[]},parent:null};return{result:await c._parseAsync({data:l.data,path:l.path,parent:W}),ctx:W}})).then(Z);{let c,W=[];for(let N of b){let Y={...l,common:{...l.common,issues:[]},parent:null},m=N._parseSync({data:l.data,path:l.path,parent:Y});if(m.status==="valid")return m;m.status==="dirty"&&!c&&(c={result:m,ctx:Y}),Y.common.issues.length&&W.push(Y.common.issues)}if(c)return l.common.issues.push(...c.ctx.common.issues),c.result;let d=W.map(N=>new zI(N));return v(l,{code:w.invalid_union,unionErrors:d}),A}}get options(){return this._def.options}};Yl.create=(G,I)=>new Yl({options:G,typeName:k.ZodUnion,...z(I)});var yG=G=>G instanceof Vl?yG(G.schema):G instanceof qI?yG(G.innerType()):G instanceof hl?[G.value]:G instanceof Rl?G.options:G instanceof Xl?M.objectValues(G.enum):G instanceof Fl?yG(G._def.innerType):G instanceof dl?[void 0]:G instanceof Nl?[null]:G instanceof SI?[void 0,...yG(G.unwrap())]:G instanceof FG?[null,...yG(G.unwrap())]:G instanceof ub||G instanceof Ql?yG(G.unwrap()):G instanceof al?yG(G._def.innerType):[],rZ=class G extends x{_parse(I){let{ctx:l}=this._processInputParams(I);if(l.parsedType!==E.object)return v(l,{code:w.invalid_type,expected:E.object,received:l.parsedType}),A;let b=this.discriminator,Z=l.data[b],c=this.optionsMap.get(Z);return c?l.common.async?c._parseAsync({data:l.data,path:l.path,parent:l}):c._parseSync({data:l.data,path:l.path,parent:l}):(v(l,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[b]}),A)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(I,l,b){let Z=new Map;for(let c of l){let W=yG(c.shape[I]);if(!W.length)throw new Error(`A discriminator value for key \`${I}\` could not be extracted from all schema options`);for(let d of W){if(Z.has(d))throw new Error(`Discriminator property ${String(I)} has duplicate value ${String(d)}`);Z.set(d,c)}}return new G({typeName:k.ZodDiscriminatedUnion,discriminator:I,options:l,optionsMap:Z,...z(b)})}};function KW(G,I){let l=RG(G),b=RG(I);if(G===I)return{valid:!0,data:G};if(l===E.object&&b===E.object){let Z=M.objectKeys(I),c=M.objectKeys(G).filter(d=>Z.indexOf(d)!==-1),W={...G,...I};for(let d of c){let N=KW(G[d],I[d]);if(!N.valid)return{valid:!1};W[d]=N.data}return{valid:!0,data:W}}else if(l===E.array&&b===E.array){if(G.length!==I.length)return{valid:!1};let Z=[];for(let c=0;c<G.length;c++){let W=G[c],d=I[c],N=KW(W,d);if(!N.valid)return{valid:!1};Z.push(N.data)}return{valid:!0,data:Z}}else return l===E.date&&b===E.date&&+G==+I?{valid:!0,data:G}:{valid:!1}}var ml=class extends x{_parse(I){let{status:l,ctx:b}=this._processInputParams(I),Z=(c,W)=>{if(UZ(c)||UZ(W))return A;let d=KW(c.value,W.value);return d.valid?((BZ(c)||BZ(W))&&l.dirty(),{status:l.value,value:d.data}):(v(b,{code:w.invalid_intersection_types}),A)};return b.common.async?Promise.all([this._def.left._parseAsync({data:b.data,path:b.path,parent:b}),this._def.right._parseAsync({data:b.data,path:b.path,parent:b})]).then(([c,W])=>Z(c,W)):Z(this._def.left._parseSync({data:b.data,path:b.path,parent:b}),this._def.right._parseSync({data:b.data,path:b.path,parent:b}))}};ml.create=(G,I,l)=>new ml({left:G,right:I,typeName:k.ZodIntersection,...z(l)});var XG=class G extends x{_parse(I){let{status:l,ctx:b}=this._processInputParams(I);if(b.parsedType!==E.array)return v(b,{code:w.invalid_type,expected:E.array,received:b.parsedType}),A;if(b.data.length<this._def.items.length)return v(b,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),A;!this._def.rest&&b.data.length>this._def.items.length&&(v(b,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),l.dirty());let c=[...b.data].map((W,d)=>{let N=this._def.items[d]||this._def.rest;return N?N._parse(new TI(b,W,b.path,d)):null}).filter(W=>!!W);return b.common.async?Promise.all(c).then(W=>HI.mergeArray(l,W)):HI.mergeArray(l,c)}get items(){return this._def.items}rest(I){return new G({...this._def,rest:I})}};XG.create=(G,I)=>{if(!Array.isArray(G))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new XG({items:G,typeName:k.ZodTuple,rest:null,...z(I)})};var OZ=class G extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(I){let{status:l,ctx:b}=this._processInputParams(I);if(b.parsedType!==E.object)return v(b,{code:w.invalid_type,expected:E.object,received:b.parsedType}),A;let Z=[],c=this._def.keyType,W=this._def.valueType;for(let d in b.data)Z.push({key:c._parse(new TI(b,d,b.path,d)),value:W._parse(new TI(b,b.data[d],b.path,d)),alwaysSet:d in b.data});return b.common.async?HI.mergeObjectAsync(l,Z):HI.mergeObjectSync(l,Z)}get element(){return this._def.valueType}static create(I,l,b){return l instanceof x?new G({keyType:I,valueType:l,typeName:k.ZodRecord,...z(b)}):new G({keyType:BG.create(),valueType:I,typeName:k.ZodRecord,...z(l)})}},Ol=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(I){let{status:l,ctx:b}=this._processInputParams(I);if(b.parsedType!==E.map)return v(b,{code:w.invalid_type,expected:E.map,received:b.parsedType}),A;let Z=this._def.keyType,c=this._def.valueType,W=[...b.data.entries()].map(([d,N],Y)=>({key:Z._parse(new TI(b,d,b.path,[Y,"key"])),value:c._parse(new TI(b,N,b.path,[Y,"value"]))}));if(b.common.async){let d=new Map;return Promise.resolve().then(async()=>{for(let N of W){let Y=await N.key,m=await N.value;if(Y.status==="aborted"||m.status==="aborted")return A;(Y.status==="dirty"||m.status==="dirty")&&l.dirty(),d.set(Y.value,m.value)}return{status:l.value,value:d}})}else{let d=new Map;for(let N of W){let Y=N.key,m=N.value;if(Y.status==="aborted"||m.status==="aborted")return A;(Y.status==="dirty"||m.status==="dirty")&&l.dirty(),d.set(Y.value,m.value)}return{status:l.value,value:d}}}};Ol.create=(G,I,l)=>new Ol({valueType:I,keyType:G,typeName:k.ZodMap,...z(l)});var Ml=class G extends x{_parse(I){let{status:l,ctx:b}=this._processInputParams(I);if(b.parsedType!==E.set)return v(b,{code:w.invalid_type,expected:E.set,received:b.parsedType}),A;let Z=this._def;Z.minSize!==null&&b.data.size<Z.minSize.value&&(v(b,{code:w.too_small,minimum:Z.minSize.value,type:"set",inclusive:!0,exact:!1,message:Z.minSize.message}),l.dirty()),Z.maxSize!==null&&b.data.size>Z.maxSize.value&&(v(b,{code:w.too_big,maximum:Z.maxSize.value,type:"set",inclusive:!0,exact:!1,message:Z.maxSize.message}),l.dirty());let c=this._def.valueType;function W(N){let Y=new Set;for(let m of N){if(m.status==="aborted")return A;m.status==="dirty"&&l.dirty(),Y.add(m.value)}return{status:l.value,value:Y}}let d=[...b.data.values()].map((N,Y)=>c._parse(new TI(b,N,b.path,Y)));return b.common.async?Promise.all(d).then(N=>W(N)):W(d)}min(I,l){return new G({...this._def,minSize:{value:I,message:s.toString(l)}})}max(I,l){return new G({...this._def,maxSize:{value:I,message:s.toString(l)}})}size(I,l){return this.min(I,l).max(I,l)}nonempty(I){return this.min(1,I)}};Ml.create=(G,I)=>new Ml({valueType:G,minSize:null,maxSize:null,typeName:k.ZodSet,...z(I)});var MZ=class G extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(I){let{ctx:l}=this._processInputParams(I);if(l.parsedType!==E.function)return v(l,{code:w.invalid_type,expected:E.function,received:l.parsedType}),A;function b(d,N){return pb({data:d,path:l.path,errorMaps:[l.common.contextualErrorMap,l.schemaErrorMap,il(),EG].filter(Y=>!!Y),issueData:{code:w.invalid_arguments,argumentsError:N}})}function Z(d,N){return pb({data:d,path:l.path,errorMaps:[l.common.contextualErrorMap,l.schemaErrorMap,il(),EG].filter(Y=>!!Y),issueData:{code:w.invalid_return_type,returnTypeError:N}})}let c={errorMap:l.common.contextualErrorMap},W=l.data;if(this._def.returns instanceof OG){let d=this;return EI(async function(...N){let Y=new zI([]),m=await d._def.args.parseAsync(N,c).catch(R=>{throw Y.addIssue(b(N,R)),Y}),V=await Reflect.apply(W,this,m);return await d._def.returns._def.type.parseAsync(V,c).catch(R=>{throw Y.addIssue(Z(V,R)),Y})})}else{let d=this;return EI(function(...N){let Y=d._def.args.safeParse(N,c);if(!Y.success)throw new zI([b(N,Y.error)]);let m=Reflect.apply(W,this,Y.data),V=d._def.returns.safeParse(m,c);if(!V.success)throw new zI([Z(m,V.error)]);return V.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...I){return new G({...this._def,args:XG.create(I).rest(sG.create())})}returns(I){return new G({...this._def,returns:I})}implement(I){return this.parse(I)}strictImplement(I){return this.parse(I)}static create(I,l,b){return new G({args:I||XG.create([]).rest(sG.create()),returns:l||sG.create(),typeName:k.ZodFunction,...z(b)})}},Vl=class extends x{get schema(){return this._def.getter()}_parse(I){let{ctx:l}=this._processInputParams(I);return this._def.getter()._parse({data:l.data,path:l.path,parent:l})}};Vl.create=(G,I)=>new Vl({getter:G,typeName:k.ZodLazy,...z(I)});var hl=class extends x{_parse(I){if(I.data!==this._def.value){let l=this._getOrReturnCtx(I);return v(l,{received:l.data,code:w.invalid_literal,expected:this._def.value}),A}return{status:"valid",value:I.data}}get value(){return this._def.value}};hl.create=(G,I)=>new hl({value:G,typeName:k.ZodLiteral,...z(I)});function em(G,I){return new Rl({values:G,typeName:k.ZodEnum,...z(I)})}var Rl=class G extends x{_parse(I){if(typeof I.data!="string"){let l=this._getOrReturnCtx(I),b=this._def.values;return v(l,{expected:M.joinValues(b),received:l.parsedType,code:w.invalid_type}),A}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(I.data)){let l=this._getOrReturnCtx(I),b=this._def.values;return v(l,{received:l.data,code:w.invalid_enum_value,options:b}),A}return EI(I.data)}get options(){return this._def.values}get enum(){let I={};for(let l of this._def.values)I[l]=l;return I}get Values(){let I={};for(let l of this._def.values)I[l]=l;return I}get Enum(){let I={};for(let l of this._def.values)I[l]=l;return I}extract(I,l=this._def){return G.create(I,{...this._def,...l})}exclude(I,l=this._def){return G.create(this.options.filter(b=>!I.includes(b)),{...this._def,...l})}};Rl.create=em;var Xl=class extends x{_parse(I){let l=M.getValidEnumValues(this._def.values),b=this._getOrReturnCtx(I);if(b.parsedType!==E.string&&b.parsedType!==E.number){let Z=M.objectValues(l);return v(b,{expected:M.joinValues(Z),received:b.parsedType,code:w.invalid_type}),A}if(this._cache||(this._cache=new Set(M.getValidEnumValues(this._def.values))),!this._cache.has(I.data)){let Z=M.objectValues(l);return v(b,{received:b.data,code:w.invalid_enum_value,options:Z}),A}return EI(I.data)}get enum(){return this._def.values}};Xl.create=(G,I)=>new Xl({values:G,typeName:k.ZodNativeEnum,...z(I)});var OG=class extends x{unwrap(){return this._def.type}_parse(I){let{ctx:l}=this._processInputParams(I);if(l.parsedType!==E.promise&&l.common.async===!1)return v(l,{code:w.invalid_type,expected:E.promise,received:l.parsedType}),A;let b=l.parsedType===E.promise?l.data:Promise.resolve(l.data);return EI(b.then(Z=>this._def.type.parseAsync(Z,{path:l.path,errorMap:l.common.contextualErrorMap})))}};OG.create=(G,I)=>new OG({type:G,typeName:k.ZodPromise,...z(I)});var qI=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===k.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(I){let{status:l,ctx:b}=this._processInputParams(I),Z=this._def.effect||null,c={addIssue:W=>{v(b,W),W.fatal?l.abort():l.dirty()},get path(){return b.path}};if(c.addIssue=c.addIssue.bind(c),Z.type==="preprocess"){let W=Z.transform(b.data,c);if(b.common.async)return Promise.resolve(W).then(async d=>{if(l.value==="aborted")return A;let N=await this._def.schema._parseAsync({data:d,path:b.path,parent:b});return N.status==="aborted"?A:N.status==="dirty"?ll(N.value):l.value==="dirty"?ll(N.value):N});{if(l.value==="aborted")return A;let d=this._def.schema._parseSync({data:W,path:b.path,parent:b});return d.status==="aborted"?A:d.status==="dirty"?ll(d.value):l.value==="dirty"?ll(d.value):d}}if(Z.type==="refinement"){let W=d=>{let N=Z.refinement(d,c);if(b.common.async)return Promise.resolve(N);if(N instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(b.common.async===!1){let d=this._def.schema._parseSync({data:b.data,path:b.path,parent:b});return d.status==="aborted"?A:(d.status==="dirty"&&l.dirty(),W(d.value),{status:l.value,value:d.value})}else return this._def.schema._parseAsync({data:b.data,path:b.path,parent:b}).then(d=>d.status==="aborted"?A:(d.status==="dirty"&&l.dirty(),W(d.value).then(()=>({status:l.value,value:d.value}))))}if(Z.type==="transform")if(b.common.async===!1){let W=this._def.schema._parseSync({data:b.data,path:b.path,parent:b});if(!UG(W))return A;let d=Z.transform(W.value,c);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:l.value,value:d}}else return this._def.schema._parseAsync({data:b.data,path:b.path,parent:b}).then(W=>UG(W)?Promise.resolve(Z.transform(W.value,c)).then(d=>({status:l.value,value:d})):A);M.assertNever(Z)}};qI.create=(G,I,l)=>new qI({schema:G,typeName:k.ZodEffects,effect:I,...z(l)});qI.createWithPreprocess=(G,I,l)=>new qI({schema:I,effect:{type:"preprocess",transform:G},typeName:k.ZodEffects,...z(l)});var SI=class extends x{_parse(I){return this._getType(I)===E.undefined?EI(void 0):this._def.innerType._parse(I)}unwrap(){return this._def.innerType}};SI.create=(G,I)=>new SI({innerType:G,typeName:k.ZodOptional,...z(I)});var FG=class extends x{_parse(I){return this._getType(I)===E.null?EI(null):this._def.innerType._parse(I)}unwrap(){return this._def.innerType}};FG.create=(G,I)=>new FG({innerType:G,typeName:k.ZodNullable,...z(I)});var Fl=class extends x{_parse(I){let{ctx:l}=this._processInputParams(I),b=l.data;return l.parsedType===E.undefined&&(b=this._def.defaultValue()),this._def.innerType._parse({data:b,path:l.path,parent:l})}removeDefault(){return this._def.innerType}};Fl.create=(G,I)=>new Fl({innerType:G,typeName:k.ZodDefault,defaultValue:typeof I.default=="function"?I.default:()=>I.default,...z(I)});var al=class extends x{_parse(I){let{ctx:l}=this._processInputParams(I),b={...l,common:{...l.common,issues:[]}},Z=this._def.innerType._parse({data:b.data,path:b.path,parent:{...b}});return xl(Z)?Z.then(c=>({status:"valid",value:c.status==="valid"?c.value:this._def.catchValue({get error(){return new zI(b.common.issues)},input:b.data})})):{status:"valid",value:Z.status==="valid"?Z.value:this._def.catchValue({get error(){return new zI(b.common.issues)},input:b.data})}}removeCatch(){return this._def.innerType}};al.create=(G,I)=>new al({innerType:G,typeName:k.ZodCatch,catchValue:typeof I.catch=="function"?I.catch:()=>I.catch,...z(I)});var jl=class extends x{_parse(I){if(this._getType(I)!==E.nan){let b=this._getOrReturnCtx(I);return v(b,{code:w.invalid_type,expected:E.nan,received:b.parsedType}),A}return{status:"valid",value:I.data}}};jl.create=G=>new jl({typeName:k.ZodNaN,...z(G)});var HQ=Symbol("zod_brand"),ub=class extends x{_parse(I){let{ctx:l}=this._processInputParams(I),b=l.data;return this._def.type._parse({data:b,path:l.path,parent:l})}unwrap(){return this._def.type}},nb=class G extends x{_parse(I){let{status:l,ctx:b}=this._processInputParams(I);if(b.common.async)return(async()=>{let c=await this._def.in._parseAsync({data:b.data,path:b.path,parent:b});return c.status==="aborted"?A:c.status==="dirty"?(l.dirty(),ll(c.value)):this._def.out._parseAsync({data:c.value,path:b.path,parent:b})})();{let Z=this._def.in._parseSync({data:b.data,path:b.path,parent:b});return Z.status==="aborted"?A:Z.status==="dirty"?(l.dirty(),{status:"dirty",value:Z.value}):this._def.out._parseSync({data:Z.value,path:b.path,parent:b})}}static create(I,l){return new G({in:I,out:l,typeName:k.ZodPipeline})}},Ql=class extends x{_parse(I){let l=this._def.innerType._parse(I),b=Z=>(UG(Z)&&(Z.value=Object.freeze(Z.value)),Z);return xl(l)?l.then(Z=>b(Z)):b(l)}unwrap(){return this._def.innerType}};Ql.create=(G,I)=>new Ql({innerType:G,typeName:k.ZodReadonly,...z(I)});function ym(G,I){let l=typeof G=="function"?G(I):typeof G=="string"?{message:G}:G;return typeof l=="string"?{message:l}:l}function gm(G,I={},l){return G?rG.create().superRefine((b,Z)=>{let c=G(b);if(c instanceof Promise)return c.then(W=>{if(!W){let d=ym(I,b),N=d.fatal??l??!0;Z.addIssue({code:"custom",...d,fatal:N})}});if(!c){let W=ym(I,b),d=W.fatal??l??!0;Z.addIssue({code:"custom",...W,fatal:d})}}):rG.create()}var pQ={object:iI.lazycreate},k;(function(G){G.ZodString="ZodString",G.ZodNumber="ZodNumber",G.ZodNaN="ZodNaN",G.ZodBigInt="ZodBigInt",G.ZodBoolean="ZodBoolean",G.ZodDate="ZodDate",G.ZodSymbol="ZodSymbol",G.ZodUndefined="ZodUndefined",G.ZodNull="ZodNull",G.ZodAny="ZodAny",G.ZodUnknown="ZodUnknown",G.ZodNever="ZodNever",G.ZodVoid="ZodVoid",G.ZodArray="ZodArray",G.ZodObject="ZodObject",G.ZodUnion="ZodUnion",G.ZodDiscriminatedUnion="ZodDiscriminatedUnion",G.ZodIntersection="ZodIntersection",G.ZodTuple="ZodTuple",G.ZodRecord="ZodRecord",G.ZodMap="ZodMap",G.ZodSet="ZodSet",G.ZodFunction="ZodFunction",G.ZodLazy="ZodLazy",G.ZodLiteral="ZodLiteral",G.ZodEnum="ZodEnum",G.ZodEffects="ZodEffects",G.ZodNativeEnum="ZodNativeEnum",G.ZodOptional="ZodOptional",G.ZodNullable="ZodNullable",G.ZodDefault="ZodDefault",G.ZodCatch="ZodCatch",G.ZodPromise="ZodPromise",G.ZodBranded="ZodBranded",G.ZodPipeline="ZodPipeline",G.ZodReadonly="ZodReadonly"})(k||(k={}));var uQ=(G,I={message:`Input not instance of ${G.name}`})=>gm(l=>l instanceof G,I),Am=BG.create,Lm=bl.create,nQ=jl.create,wQ=Zl.create,km=cl.create,vQ=Wl.create,JQ=Bl.create,EQ=dl.create,yQ=Nl.create,sQ=rG.create,tQ=sG.create,CQ=cG.create,eQ=rl.create,gQ=tG.create,AQ=iI.create,LQ=iI.strictCreate,kQ=Yl.create,oQ=rZ.create,zQ=ml.create,iQ=XG.create,xQ=OZ.create,UQ=Ol.create,BQ=Ml.create,rQ=MZ.create,OQ=Vl.create,MQ=hl.create,jQ=Rl.create,KQ=Xl.create,DQ=OG.create,SQ=qI.create,TQ=SI.create,qQ=FG.create,fQ=qI.createWithPreprocess,PQ=nb.create,_Q=()=>Am().optional(),$Q=()=>Lm().optional(),IH=()=>km().optional(),GH={string:(G=>BG.create({...G,coerce:!0})),number:(G=>bl.create({...G,coerce:!0})),boolean:(G=>cl.create({...G,coerce:!0})),bigint:(G=>Zl.create({...G,coerce:!0})),date:(G=>Wl.create({...G,coerce:!0}))};var lH=A;var bH=xI.enum(["read-only","workspace-write","full-auto"]).default("read-only"),ZH=xI.object({id:xI.string(),type:xI.string(),enabled:xI.boolean().default(!0),executionPolicy:bH,config:xI.record(xI.unknown()).default({})}),cH=xI.enum(["default-only","auto"]).default("default-only"),WH=xI.object({defaultProvider:xI.string().optional(),selectionPolicy:cH,providers:xI.array(ZH).min(1,"At least one provider required")});function om(G){let I=WH.parse(G);return{defaultProvider:I.defaultProvider,selectionPolicy:I.selectionPolicy,providers:I.providers,enabledProviders:I.providers.filter(l=>l.enabled)}}KZ();qW();import{mkdirSync as Om,readFileSync as AI,readdirSync as PW,existsSync as MG,unlinkSync as uH,rmdirSync as nH}from"fs";import{join as P}from"path";import{spawn as Mm}from"child_process";import{randomUUID as wH}from"crypto";var vH=3e5,JH=".agestra/.jobs",EH=3e4,yH=100,sH=7,SZ=class{jobsDir;maxJobs;maxAgeDays;submitCount=0;statusCache=new Map;constructor(I=process.cwd(),l){this.jobsDir=P(I,JH),Om(this.jobsDir,{recursive:!0}),this.maxJobs=l?.maxJobs??yH,this.maxAgeDays=l?.maxAgeDays??sH}submit(I){let l=`${I.provider}-${Date.now()}-${wH().slice(0,6)}`,b=P(this.jobsDir,l);Om(b,{recursive:!0});let Z={id:l,provider:I.provider,prompt:I.prompt,timeout:I.timeout??vH,createdAt:new Date().toISOString(),cliCommand:I.cliCommand,cliArgs:I.cliArgs},c={id:l,state:"queued",provider:I.provider};return yI(P(b,"job.json"),Z),yI(P(b,"status.json"),c),XI(P(b,"prompt.txt"),I.prompt),this.statusCache.set(l,c),this.spawnWorker(b),this.submitCount++,this.submitCount%10===0&&this.cleanup(),l}getStatus(I){if(!DZ(I))return null;let l=["completed","error","timed_out","cancelled","missing_cli"],b=this.statusCache.get(I);if(b&&l.includes(b.state))return b;let Z=P(this.jobsDir,I,"status.json");if(!MG(Z))return null;let c=JSON.parse(AI(Z,"utf-8"));if(c.state==="queued"){let W=P(this.jobsDir,I,"job.json");try{let d=JSON.parse(AI(W,"utf-8"));if(Date.now()-new Date(d.createdAt).getTime()>EH){let Y={...c,state:"error",completedAt:new Date().toISOString()};return yI(Z,Y),XI(P(this.jobsDir,I,"error.txt"),"Job stalled in queued state (worker failed to start)"),this.statusCache.set(I,Y),Y}}catch{}}return this.statusCache.set(I,c),c}getResult(I){if(!DZ(I))return null;let l=this.getStatus(I);if(!l)return null;let b=P(this.jobsDir,I),Z={id:I,state:l.state,exitCode:l.exitCode},c=P(b,"output.txt");MG(c)&&(Z.output=AI(c,"utf-8"));let W=P(b,"error.txt");return MG(W)&&(Z.error=AI(W,"utf-8")),Z}listJobs(){if(!MG(this.jobsDir))return[];let I=PW(this.jobsDir,{withFileTypes:!0}).filter(b=>b.isDirectory()),l=[];for(let b of I){let Z=P(this.jobsDir,b.name,"status.json");MG(Z)&&l.push(JSON.parse(AI(Z,"utf-8")))}return l}cancel(I){if(!DZ(I))return!1;let l=this.getStatus(I);if(!l||l.state!=="queued"&&l.state!=="running")return!1;let b=P(this.jobsDir,I),Z={...l,state:"cancelled",completedAt:new Date().toISOString()};return yI(P(b,"status.json"),Z),this.statusCache.set(I,Z),!0}cleanup(){if(!MG(this.jobsDir))return 0;let I=PW(this.jobsDir,{withFileTypes:!0}).filter(Y=>Y.isDirectory()),l=[];for(let Y of I){let m=P(this.jobsDir,Y.name,"status.json"),V=P(this.jobsDir,Y.name,"job.json");if(!MG(m))continue;let h=JSON.parse(AI(m,"utf-8")),R=null;try{R=JSON.parse(AI(V,"utf-8"))}catch{}l.push({name:Y.name,status:h,descriptor:R})}let b=["completed","error","timed_out","cancelled","missing_cli"],Z=l.filter(Y=>b.includes(Y.status.state)).sort((Y,m)=>{let V=Y.descriptor?.createdAt??"",h=m.descriptor?.createdAt??"";return V.localeCompare(h)}),c=0,W=Date.now(),d=this.maxAgeDays*24*60*60*1e3,N=l.length;for(let Y of Z){let V=(Y.descriptor?.createdAt?W-new Date(Y.descriptor.createdAt).getTime():1/0)>d,h=N-c>this.maxJobs;if(!V&&!h)continue;let R=P(this.jobsDir,Y.name);try{let X=PW(R);for(let F of X)uH(P(R,F));nH(R),this.statusCache.delete(Y.name),c++}catch{}}return c}spawnWorker(I){let l=new URL("./job-worker.js",import.meta.url).pathname;if(MG(l)){let b=Mm(process.execPath,[l,I],{detached:!0,stdio:"ignore"});b.on("error",()=>{this.runInProcess(I)}),b.unref()}else this.runInProcess(I)}runInProcess(I){Promise.resolve().then(()=>(rm(),Bm)).then(({resolveCliConfig:l})=>{let b;try{b=JSON.parse(AI(P(I,"job.json"),"utf-8"))}catch{return}let Z=l(b);if(!Z){let F=P(I,"status.json"),H=JSON.parse(AI(F,"utf-8"));yI(F,{...H,state:"missing_cli",completedAt:new Date().toISOString()}),XI(P(I,"error.txt"),`No CLI mapping for provider: ${b.provider}`);return}let{command:c,buildArgs:W}=Z,d=AI(P(I,"prompt.txt"),"utf-8"),N=W(d),Y=P(I,"status.json"),m=JSON.parse(AI(Y,"utf-8"));yI(Y,{...m,state:"running",startedAt:new Date().toISOString()});let V=Mm(c,N,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),h="",R="";V.stdout.on("data",F=>{h+=F.toString()}),V.stderr.on("data",F=>{R+=F.toString()});let X=setTimeout(()=>{V.kill("SIGTERM"),setTimeout(()=>{try{V.kill("SIGKILL")}catch{}},3e3),XI(P(I,"output.txt"),h),XI(P(I,"error.txt"),R);let F=JSON.parse(AI(Y,"utf-8"));yI(Y,{...F,state:"timed_out",completedAt:new Date().toISOString()})},b.timeout);V.on("close",F=>{clearTimeout(X),XI(P(I,"output.txt"),h),XI(P(I,"error.txt"),R);let H=JSON.parse(AI(Y,"utf-8"));yI(Y,{...H,state:F===0?"completed":"error",exitCode:F??1,completedAt:new Date().toISOString()})}),V.on("error",F=>{clearTimeout(X),XI(P(I,"error.txt"),F.message);let H=JSON.parse(AI(Y,"utf-8"));yI(Y,{...H,state:"missing_cli",completedAt:new Date().toISOString()})})}).catch(()=>{try{let l=P(I,"status.json"),b=JSON.parse(AI(l,"utf-8"));yI(l,{...b,state:"error",completedAt:new Date().toISOString()}),XI(P(I,"error.txt"),"Failed to load job worker module")}catch{}})}};KZ();import{mkdirSync as tH,readdirSync as jm,readFileSync as CH,unlinkSync as eH}from"fs";import{join as yb}from"path";function Km(G){let I=G.getFullYear(),l=String(G.getMonth()+1).padStart(2,"0"),b=String(G.getDate()).padStart(2,"0");return`${I}-${l}-${b}`}function gH(G){return typeof G=="object"&&G!==null&&"traceId"in G&&"action"in G&&!("type"in G&&G.type==="quality_update")}function AH(G){return typeof G=="object"&&G!==null&&"type"in G&&G.type==="quality_update"}var TZ=class{tracesDir;writer;constructor(I,l){this.tracesDir=yb(I,".agestra","traces"),tH(this.tracesDir,{recursive:!0}),this.writer=new jZ(l)}write(I){let l={...I,timestamp:I.timestamp??new Date().toISOString()},b=Km(new Date(l.timestamp)),Z=yb(this.tracesDir,`${b}.jsonl`);this.writer.append(Z,JSON.stringify(l)+`
11
11
  `,"trace")}query(I={}){let l=this.listFiles(I.daysBack),b=[],Z=[];for(let W of l){let d=CH(W,"utf-8").split(`
12
12
  `).filter(Boolean);for(let N of d)try{let Y=JSON.parse(N);AH(Y)?Z.push(Y):gH(Y)&&b.push(Y)}catch{}}for(let W of Z){let d=b.find(N=>N.traceId===W.traceId&&N.providerId===W.providerId);d&&(d.quality=W.quality)}let c=b;return I.providerId&&(c=c.filter(W=>W.providerId===I.providerId)),I.task&&(c=c.filter(W=>W.task===I.task)),I.traceId&&(c=c.filter(W=>W.traceId===I.traceId)),I.successOnly&&(c=c.filter(W=>W.response.success)),I.failedOnly&&(c=c.filter(W=>!W.response.success)),I.limit!==void 0&&(c=c.slice(0,I.limit)),c}updateQuality(I,l,b){let Z=new Date,c={type:"quality_update",traceId:I,providerId:l,timestamp:Z.toISOString(),quality:b},W=Km(Z),d=yb(this.tracesDir,`${W}.jsonl`);this.writer.append(d,JSON.stringify(c)+`
13
- `,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(I){let l=this.query({daysBack:I}),b=new Map;for(let c of l){if(!c.quality)continue;let W=`${c.providerId}:${c.task}`,d=b.get(W)??{totalScore:0,count:0,totalLatency:0};d.totalScore+=c.quality.score,d.count+=1,d.totalLatency+=c.latencyMs,b.set(W,d)}let Z=new Map;for(let[c,W]of b)Z.set(c,{avgScore:W.totalScore/W.count,count:W.count,avgLatencyMs:W.totalLatency/W.count});return Z}cleanup(I){let l=new Date;l.setDate(l.getDate()-I);let b=0,Z;try{Z=jm(this.tracesDir)}catch{return 0}for(let c of Z){if(!c.endsWith(".jsonl"))continue;let W=c.replace(".jsonl",""),d=new Date(W+"T00:00:00.000Z");isNaN(d.getTime())||d<l&&(eH(yb(this.tracesDir,c)),b++)}return b}listFiles(I){let l;try{l=jm(this.tracesDir).filter(b=>b.endsWith(".jsonl")).sort()}catch{return[]}if(I!==void 0){let b=new Date;b.setDate(b.getDate()-I),l=l.filter(Z=>{let c=Z.replace(".jsonl",""),W=new Date(c+"T00:00:00.000Z");return!isNaN(W.getTime())&&W>=b})}return l.map(b=>yb(this.tracesDir,b))}};var Dm="4.3.1",qZ="http://localhost:11434";var Sm="llama3";var fZ=class{upstream;cached=null;cachedAt=0;cachedDaysBack=0;ttlMs;constructor(I,l){this.upstream=I,this.ttlMs=l?.ttlMs??6e4}getQualityStats(I){let l=Date.now();return this.cached!==null&&this.cachedDaysBack===I&&l-this.cachedAt<this.ttlMs?this.cached:(this.cached=this.upstream.getQualityStats(I),this.cachedAt=l,this.cachedDaysBack=I,this.cached)}invalidate(){this.cached=null,this.cachedAt=0}};var PZ=class{maxConcurrent;maxQueueSize;running=0;queue=[];constructor(I,l=16){this.maxConcurrent=I,this.maxQueueSize=l}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}if(this.queue.length>=this.maxQueueSize)throw new Error(`ConcurrencyLimiter queue full (max ${this.maxQueueSize})`);return new Promise(I=>{this.queue.push(()=>{this.running++,I()})})}release(){this.running--;let I=this.queue.shift();I&&I()}async run(I){await this.acquire();try{return await I()}finally{this.release()}}};import{spawn as LH}from"child_process";var kH=3e5,oH=3,zH=15e3,iH=3e3,xH=12e4,_Z=class{state="idle";process=null;consecutiveFailures=0;idleTimer=null;pendingRequests=new Map;command;commandPrefix;idleTimeoutMs;maxConsecutiveFailures;startupTimeoutMs;stdoutBuffer="";startupResolve=null;startupReject=null;constructor(I){this.command=I.command,this.commandPrefix=I.commandPrefix??[],this.idleTimeoutMs=I.idleTimeoutMs??kH,this.maxConsecutiveFailures=I.maxConsecutiveFailures??oH,this.startupTimeoutMs=I.startupTimeoutMs??zH}async request(I,l){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(I,l??xH)}isAlive(){return this.process!==null&&!this.process.killed&&(this.state==="ready"||this.state==="busy"||this.state==="starting")}getState(){return this.state}shouldFallback(){return this.consecutiveFailures>=this.maxConsecutiveFailures}async shutdown(){if(!this.process||this.state==="shutdown"||this.state==="idle")return;this.state="shutdown",this.clearIdleTimer();for(let[,b]of this.pendingRequests)clearTimeout(b.timer),b.reject(new Error("App server shutting down"));this.pendingRequests.clear(),this.startupReject&&(this.startupReject(new Error("App server shutting down")),this.startupResolve=null,this.startupReject=null);let I=this.process;this.process=null;try{I.kill("SIGTERM")}catch{this.state="idle";return}let l=setTimeout(()=>{try{I.kill("SIGKILL")}catch{}},iH);await new Promise(b=>{I.on("close",()=>{clearTimeout(l),b()}),(I.exitCode!==null||I.signalCode!==null)&&(clearTimeout(l),b())}),this.state="idle"}async start(){if(this.state!=="idle"&&this.state!=="error")return;this.state="starting",this.stdoutBuffer="";let I=[...this.commandPrefix,"--app-server"];return this.process=LH(this.command,I,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0}),this.process.stdout.on("data",l=>{this.handleStdout(l.toString())}),this.process.stderr.on("data",l=>{process.stderr.write(`[codex-app-server] ${l.toString()}`)}),this.process.on("close",(l,b)=>{this.handleProcessClose(l,b)}),this.process.on("error",l=>{this.handleProcessError(l)}),this.waitForReady()}waitForReady(){return this.state==="ready"?Promise.resolve():new Promise((I,l)=>{this.startupResolve=I,this.startupReject=l;let b=setTimeout(()=>{this.startupResolve=null,this.startupReject=null,this.consecutiveFailures++,this.state="error",l(new Error(`CodexAppServer startup timeout (${this.startupTimeoutMs}ms)`))},this.startupTimeoutMs),Z=this.startupResolve;this.startupResolve=()=>{clearTimeout(b),Z?.()};let c=this.startupReject;this.startupReject=W=>{clearTimeout(b),c?.(W)}})}handleStdout(I){this.stdoutBuffer+=I;let l;for(;(l=this.stdoutBuffer.indexOf(`
13
+ `,"audit")}shutdown(){this.writer.destroy()}panicFlush(){this.writer.panicFlush()}getQualityStats(I){let l=this.query({daysBack:I}),b=new Map;for(let c of l){if(!c.quality)continue;let W=`${c.providerId}:${c.task}`,d=b.get(W)??{totalScore:0,count:0,totalLatency:0};d.totalScore+=c.quality.score,d.count+=1,d.totalLatency+=c.latencyMs,b.set(W,d)}let Z=new Map;for(let[c,W]of b)Z.set(c,{avgScore:W.totalScore/W.count,count:W.count,avgLatencyMs:W.totalLatency/W.count});return Z}cleanup(I){let l=new Date;l.setDate(l.getDate()-I);let b=0,Z;try{Z=jm(this.tracesDir)}catch{return 0}for(let c of Z){if(!c.endsWith(".jsonl"))continue;let W=c.replace(".jsonl",""),d=new Date(W+"T00:00:00.000Z");isNaN(d.getTime())||d<l&&(eH(yb(this.tracesDir,c)),b++)}return b}listFiles(I){let l;try{l=jm(this.tracesDir).filter(b=>b.endsWith(".jsonl")).sort()}catch{return[]}if(I!==void 0){let b=new Date;b.setDate(b.getDate()-I),l=l.filter(Z=>{let c=Z.replace(".jsonl",""),W=new Date(c+"T00:00:00.000Z");return!isNaN(W.getTime())&&W>=b})}return l.map(b=>yb(this.tracesDir,b))}};var Dm="4.3.2",qZ="http://localhost:11434";var Sm="llama3";var fZ=class{upstream;cached=null;cachedAt=0;cachedDaysBack=0;ttlMs;constructor(I,l){this.upstream=I,this.ttlMs=l?.ttlMs??6e4}getQualityStats(I){let l=Date.now();return this.cached!==null&&this.cachedDaysBack===I&&l-this.cachedAt<this.ttlMs?this.cached:(this.cached=this.upstream.getQualityStats(I),this.cachedAt=l,this.cachedDaysBack=I,this.cached)}invalidate(){this.cached=null,this.cachedAt=0}};var PZ=class{maxConcurrent;maxQueueSize;running=0;queue=[];constructor(I,l=16){this.maxConcurrent=I,this.maxQueueSize=l}async acquire(){if(this.running<this.maxConcurrent){this.running++;return}if(this.queue.length>=this.maxQueueSize)throw new Error(`ConcurrencyLimiter queue full (max ${this.maxQueueSize})`);return new Promise(I=>{this.queue.push(()=>{this.running++,I()})})}release(){this.running--;let I=this.queue.shift();I&&I()}async run(I){await this.acquire();try{return await I()}finally{this.release()}}};import{spawn as LH}from"child_process";var kH=3e5,oH=3,zH=15e3,iH=3e3,xH=12e4,_Z=class{state="idle";process=null;consecutiveFailures=0;idleTimer=null;pendingRequests=new Map;command;commandPrefix;idleTimeoutMs;maxConsecutiveFailures;startupTimeoutMs;stdoutBuffer="";startupResolve=null;startupReject=null;constructor(I){this.command=I.command,this.commandPrefix=I.commandPrefix??[],this.idleTimeoutMs=I.idleTimeoutMs??kH,this.maxConsecutiveFailures=I.maxConsecutiveFailures??oH,this.startupTimeoutMs=I.startupTimeoutMs??zH}async request(I,l){if(this.state==="shutdown")throw new Error("CodexAppServer is shutting down");if((this.state==="idle"||this.state==="error")&&await this.start(),this.state==="starting"&&await this.waitForReady(),this.state!=="ready"&&this.state!=="busy")throw new Error(`CodexAppServer in unexpected state: ${this.state}`);return this.sendRequest(I,l??xH)}isAlive(){return this.process!==null&&!this.process.killed&&(this.state==="ready"||this.state==="busy"||this.state==="starting")}getState(){return this.state}shouldFallback(){return this.consecutiveFailures>=this.maxConsecutiveFailures}async shutdown(){if(!this.process||this.state==="shutdown"||this.state==="idle")return;this.state="shutdown",this.clearIdleTimer();for(let[,b]of this.pendingRequests)clearTimeout(b.timer),b.reject(new Error("App server shutting down"));this.pendingRequests.clear(),this.startupReject&&(this.startupReject(new Error("App server shutting down")),this.startupResolve=null,this.startupReject=null);let I=this.process;this.process=null;try{I.kill("SIGTERM")}catch{this.state="idle";return}let l=setTimeout(()=>{try{I.kill("SIGKILL")}catch{}},iH);await new Promise(b=>{I.on("close",()=>{clearTimeout(l),b()}),(I.exitCode!==null||I.signalCode!==null)&&(clearTimeout(l),b())}),this.state="idle"}async start(){if(this.state!=="idle"&&this.state!=="error")return;this.state="starting",this.stdoutBuffer="";let I=[...this.commandPrefix,"--app-server"];return this.process=LH(this.command,I,{stdio:["pipe","pipe","pipe"],detached:!1,windowsHide:!0}),this.process.stdout.on("data",l=>{this.handleStdout(l.toString())}),this.process.stderr.on("data",l=>{process.stderr.write(`[codex-app-server] ${l.toString()}`)}),this.process.on("close",(l,b)=>{this.handleProcessClose(l,b)}),this.process.on("error",l=>{this.handleProcessError(l)}),this.waitForReady()}waitForReady(){return this.state==="ready"?Promise.resolve():new Promise((I,l)=>{this.startupResolve=I,this.startupReject=l;let b=setTimeout(()=>{this.startupResolve=null,this.startupReject=null,this.consecutiveFailures++,this.state="error",l(new Error(`CodexAppServer startup timeout (${this.startupTimeoutMs}ms)`))},this.startupTimeoutMs),Z=this.startupResolve;this.startupResolve=()=>{clearTimeout(b),Z?.()};let c=this.startupReject;this.startupReject=W=>{clearTimeout(b),c?.(W)}})}handleStdout(I){this.stdoutBuffer+=I;let l;for(;(l=this.stdoutBuffer.indexOf(`
14
14
  `))!==-1;){let b=this.stdoutBuffer.slice(0,l).trim();if(this.stdoutBuffer=this.stdoutBuffer.slice(l+1),!!b){if(this.state==="starting"&&(b.includes("ready")||b.includes("initialized"))){this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null);continue}try{let Z=JSON.parse(b);if(Z.id&&this.pendingRequests.has(Z.id)){let c=this.pendingRequests.get(Z.id);this.pendingRequests.delete(Z.id),clearTimeout(c.timer),this.consecutiveFailures=0,this.pendingRequests.size===0&&(this.state="ready",this.resetIdleTimer()),c.resolve(Z)}}catch{this.state==="starting"&&(this.state="ready",this.consecutiveFailures=0,this.resetIdleTimer(),this.startupResolve&&(this.startupResolve(),this.startupResolve=null,this.startupReject=null))}}}}sendRequest(I,l){return new Promise((b,Z)=>{if(!this.process||!this.process.stdin){Z(new Error("App server process not available"));return}let c=setTimeout(()=>{this.pendingRequests.delete(I.id),this.consecutiveFailures++,this.pendingRequests.size===0&&this.state==="busy"&&(this.state="error"),Z(new Error(`App server request timeout (${l}ms)`))},l);this.pendingRequests.set(I.id,{resolve:b,reject:Z,timer:c}),this.state="busy",this.clearIdleTimer();try{this.process.stdin.write(JSON.stringify(I)+`
15
15
  `)}catch(W){clearTimeout(c),this.pendingRequests.delete(I.id),this.consecutiveFailures++,this.state="error",Z(new Error(`Failed to write to app server: ${W.message}`))}})}handleProcessClose(I,l){for(let[,b]of this.pendingRequests)clearTimeout(b.timer),b.reject(new Error(`App server process exited (code=${I}, signal=${l})`));this.pendingRequests.clear(),this.startupReject&&(this.consecutiveFailures++,this.startupReject(new Error(`App server process exited during startup (code=${I})`)),this.startupResolve=null,this.startupReject=null),this.process=null,this.clearIdleTimer(),this.state!=="shutdown"&&(this.state=this.state==="starting"?"error":"idle")}handleProcessError(I){this.consecutiveFailures++,this.startupReject&&(this.startupReject(new Error(`App server spawn error: ${I.message}`)),this.startupResolve=null,this.startupReject=null),this.state="error",this.process=null,this.clearIdleTimer()}resetIdleTimer(){this.clearIdleTimer(),this.idleTimer=setTimeout(()=>{this.state==="ready"&&this.pendingRequests.size===0&&this.shutdown().catch(()=>{})},this.idleTimeoutMs),this.idleTimer&&typeof this.idleTimer.unref=="function"&&this.idleTimer.unref()}clearIdleTimer(){this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}};async function Tm(G){let I=await fetch(`${G}/api/tags`);if(!I.ok)throw new Error(`Ollama API error: ${I.status}`);return((await I.json()).models||[]).map(b=>({name:b.name,size:b.size||0,strengths:UH(b.name)}))}function UH(G){let I=["chat"],l=G.toLowerCase();return(l.includes("coder")||l.includes("code"))&&I.push("code_review","code_generation"),l.includes("instruct")&&I.push("instruction_following"),l.includes("embed")&&I.push("embedding"),I}var Hl=class G{id;type="ollama";host;defaultModel;maxContext;available=!1;unavailableUntil=0;models=[];timeouts;static RATE_LIMIT_BACKOFF_MS=6e4;constructor(I){this.id=I.id,this.host=I.host,this.defaultModel=I.defaultModel||"auto",this.maxContext=I.maxContext??32768,this.timeouts={default:I.timeouts?.default??3e4,generate:I.timeouts?.generate??3e5,chat:I.timeouts?.chat??3e5}}async initialize(){try{this.models=await Tm(this.host),this.available=this.models.length>0}catch{this.available=!1}}async healthCheck(){try{let I=await fetch(`${this.host}/api/tags`);if(!I.ok)return{status:"error",message:`HTTP ${I.status}`};let l=await I.json(),b=l.models?.length??0;return{status:b>0?"ok":"degraded",message:`${b} models available`,details:{models:l.models?.map(Z=>Z.name)}}}catch(I){return{status:"error",message:I.message}}}getCapabilities(){return{maxContext:this.maxContext,supportsSystemPrompt:!0,supportsFiles:!1,supportsStreaming:!0,supportsJsonOutput:!1,supportsToolUse:!0,strengths:[...new Set(this.models.flatMap(I=>I.strengths))],models:this.models.map(I=>({name:I.name,description:`Ollama model (${Math.round(I.size/1e9)}GB)`,strengths:I.strengths}))}}isAvailable(){return this.unavailableUntil>0&&Date.now()<this.unavailableUntil?!1:(this.unavailableUntil>0&&Date.now()>=this.unavailableUntil&&(this.unavailableUntil=0),this.available)}async chat(I){if(!this.available)throw new QI(this.id,"Ollama not running or no models installed");let l=I.model||this.selectModel(),b={model:l,prompt:I.prompt,system:I.system||"You are a helpful assistant.",stream:!1,...I.extra||{}},Z=new AbortController,c=setTimeout(()=>Z.abort(),this.timeouts.generate);try{let W=await fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b),signal:Z.signal});if(W.status===429)throw this.unavailableUntil=Date.now()+G.RATE_LIMIT_BACKOFF_MS,new QI(this.id,`Rate limited (429) \u2014 temporarily deactivated for ${G.RATE_LIMIT_BACKOFF_MS/1e3}s`);if(!W.ok)throw new gI(this.id,`HTTP ${W.status}: ${W.statusText}`);let d=await W.json();return{text:d.response,model:d.model||l,provider:this.id}}catch(W){throw W.name==="AbortError"?new xG(this.id,this.timeouts.generate):W instanceof gI||W instanceof QI?W:new gI(this.id,W.message)}finally{clearTimeout(c)}}selectModel(){if(this.defaultModel!=="auto")return this.defaultModel;if(this.models.length===0)throw new QI(this.id,`No models detected. Install a model first (ollama pull ${Sm})`);return this.models[0].name}getModels(){return[...this.models]}getConnectionInfo(){return{host:this.host,model:this.selectModel()}}};var rH=[/^Loaded cached credentials/i,/^\[debug\]/i,/^\[info\]/i,/^\[warn\]/i,/^Using /i,/^Model:/i];function qm(G){return G.split(`
16
16
  `).filter(b=>{let Z=b.trim();return Z?!rH.some(c=>c.test(Z)):!1}).join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agestra",
3
- "version": "4.3.1",
3
+ "version": "4.3.2",
4
4
  "description": "Claude Code plugin — orchestrate Ollama, Gemini, and Codex for multi-AI debates, cross-validation, and GraphRAG memory",
5
5
  "type": "module",
6
6
  "packageManager": "npm@11.11.0",
package/skills/cancel.md CHANGED
@@ -16,9 +16,7 @@ Check for active operations in this order:
16
16
 
17
17
  1. **CLI Workers** — Call `cli_worker_status` to check for workers in RUNNING or SPAWNING state
18
18
  2. **Debate** — Call `agent_debate_status` to check for active debates
19
- 3. **Task Chain** — Call `agent_task_chain_status` to check for running chains
20
- 4. **Task** — Call `agent_task_status` for individual running tasks
21
- 5. **Background agents** — Check for any spawned background agents still running
19
+ 3. **Background agents** — Check for any spawned background agents still running
22
20
 
23
21
  If nothing is detected as active, inform the user: "No active Agestra operations found."
24
22
 
@@ -42,7 +42,7 @@ Models change frequently. Always call `ollama_models` before assigning tasks.
42
42
  ### Gemini / Codex (Cloud)
43
43
 
44
44
  Full-capability agents. Use for:
45
- - Complex tasks via `ai_chat` or `agent_assign_task` (text response)
45
+ - Complex tasks via `ai_chat` (text response)
46
46
  - Autonomous coding via `cli_worker_spawn` (file modifications in worktree)
47
47
  - Parallel work and as validators
48
48
 
@@ -103,13 +103,13 @@ Match by **semantic intent**, not literal keywords. These triggers apply in any
103
103
  | Code review, review request | `/agestra review` or `workspace_create_review` | User asks to review code, PR, or implementation |
104
104
  | Second opinion, other perspectives | `ai_compare` or `/agestra review` (각자 독립) | User wants multiple viewpoints on a decision |
105
105
  | Validation, verification, cross-check | `agent_cross_validate` | User wants to confirm correctness of work output |
106
- | Speed up, parallelize, split work | `agent_dispatch` or CLI workers | User wants faster execution or has independent tasks |
106
+ | Speed up, parallelize, split work | Team API or CLI workers | User wants faster execution or has independent tasks |
107
107
  | Past experience, history, previous attempts | `memory_search` or `memory_dead_ends` | User asks about prior work or known issues |
108
108
  | Remember this, save for later | `memory_store` | User wants to persist knowledge across sessions |
109
- | Mention a provider by name (Gemini, Codex, Ollama) | `ai_chat` or `agent_assign_task` | Route directly to the named provider |
109
+ | Mention a provider by name (Gemini, Codex, Ollama) | `ai_chat` or `cli_worker_spawn` | Route directly to the named provider |
110
110
  | Architecture review, design discussion | `/agestra design` | Structured multi-AI architecture exploration |
111
111
  | Compare options, which is better | `ai_compare` | Side-by-side comparison from multiple providers |
112
- | Large refactoring, many files to change | CLI workers or `agent_dispatch` | Split by file/module for parallel processing |
112
+ | Large refactoring, many files to change | CLI workers or Team API workers | Split by file/module for parallel processing |
113
113
  | About to commit, create PR, finalize work | `agent_cross_validate` | Pre-commit validation by other AI providers |
114
114
  | Check worker status, manage workers | `worker-manage` skill | User asks about running workers |
115
115